Help me to avoid multiple inheritance aka. help me

2019-09-04 05:59发布

I have two classes LightA and LightB. I have the source code of LightB but not that of LightA. I extended LightB with LightDimDip. ie LightDimDip:extends LightB. Now I need to apply DimDip feature to lightB also.

Can any one suggest good OOP design.

Once again I remind you people that I cannot modify LightA.

1条回答
我只想做你的唯一
2楼-- · 2019-09-04 06:48

Do the lights have a common interface? In which case I guess you could use the decorator pattern here

interface ILight { int GetIntensity() }
class LightA : ILight { int GetIntentisy(){ return 10; } }
class LightB : ILight { int GetIntensity(){ return 15; } }

class DimLight : ILight {
     public DimLight(ILight inner){}

     //Add behaviour inner
     int GetIntensity(){ return inner.GetIntensity() / 2; }
}

ILight dimLightA = new DimLight(new LightA())
ILight dimLightB = new DimLight(new LightB())

Then you can put the light behaviour in the DimLight class and apply it to any class which implements ILight.

查看更多
登录 后发表回答