samedi 24 février 2018

Is the decorator pattern the correct pattern to be used on this situation

I would like to ask if the decorator pattern suits my needs and is another way to make my software design much better?

Previously I have a device which is always on all the time. On the code below, that is the Device class. Now, to conserve some battery life, I need to turn it off then On again. I created a DeviceWithOnOffDecorator class. I used decorator pattern which I think helped a lot in avoiding modifications on the Device class. But having On and Off on every operation, I feel that the code doesn't conform to DRY principle.

namespace Decorator
{
    interface IDevice
    {
        byte[] GetData();
        void SendData();
    }


    class Device : IDevice
    {
        public byte[] GetData() {return new byte[] {1,2,3 }; }
        public void SendData() {Console.WriteLine("Sending Data"); }
    }


    // new requirement, the device needs to be turned on and turned off
    // after each operation to save some Battery Power
    class DeviceWithOnOffDecorator:IDevice
    {
        IDevice mIdevice;

        public DeviceWithOnOffDecorator(IDevice d)
        {
            this.mIdevice = d;
            Off();
        }

        void Off() { Console.WriteLine("Off");}
        void On() { Console.WriteLine("On"); }

        public byte[] GetData()
        {
            On();
            var b = mIdevice.GetData();
            Off();
            return b;
        }


        public void SendData()
        {
            On();
            mIdevice.SendData();
            Off();
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Device device = new Device();
            DeviceWithOnOffDecorator devicewithOnOff = new DeviceWithOnOffDecorator(device);
            IDevice iDevice = devicewithOnOff;

            var data = iDevice.GetData();
            iDevice.SendData();
        }
    }
}

On this example: I just have two operations only GetData and SendData, but on the actual software there are lots of operations involved and I need to do enclose each operations with On and Off,

void AnotherOperation1()
{
On();
// do all stuffs here
Off();
}

byte AnotherOperation2()
{
On();
byte b;
// do all stuffs here
Off();
return b;
}

I feel that enclosing each function with On and Off is repetitive and is there a way to improve this?

Aucun commentaire:

Enregistrer un commentaire