开发者

How to remove decorators out of order in C#

开发者 https://www.devze.com 2023-04-11 02:58 出处:网络
I\'m trying to implement a simple App that let me choose extras in a car. Each extra item is a decorator for a base class Car.

I'm trying to implement a simple App that let me choose extras in a car. Each extra item is a decorator for a base class Car.

Let's say i do the following

Car p = ne开发者_如何学JAVAw FordFusion();
p = new ElectricWindows(p);
p = new LeatherSeatings(p);
p = new Airbags(p);

then my object p will be a Ford Fusion with Electric Windows, Leather Seatings and Airbags.

I need to let the user remove the decorators out of order, like, let's say, remove the Electric Windows without removing Leather Seatings and Airbags


Sounds like a decorator pattern may not be the best way to model your domain. Do your decorators really need to change the behavior of the car? Or do they just add to the cost/price?

Have you tried having a collection of ICarFeatures as a member of the Car class? ICarFeature could have a GetCost method or something of the sort to allow adding up the total cost of the car.


I would probably tackle this problem with Chain of responsibility. I would create a handler interface

public interface IAccessoryHandler
{ 
  bool CanHandle( UserOption option );  // UserOption is an enum of Electric Window etc.

  Handle( Car car ); 
}

Then i'd create handler implementaions i.e. ElectricWindowHandler, LeatherHandler etc, for example CanHandle() => if option == UserOption.electric then Handle() => car.Accessories.Add( new ElectricWindow);

Every time the user changes the options, i'd clear the car accessories collection, do a foreach on selected user options and have the car object run through the chain. By the end of the chain process, you car will have correct accessories.


May be have a centralized objects which tell you for which model which features have been deprecated, so that you dont have to change every decorator pattern entirely. Just a small modification in them, i mean before the ElectricWindows return the Car object, it check if its qualifies to have this feature. Hope i am making sense!!


My answer assumes that you will not abandon the decorator approach.

In your question you stipulate being able to remove Decorators out of order, this basically puts the kibosh on recommending the Undo/Redo or Decorate/UnDecorate approach.

I thought that you might leverage the Memento pattern. Tracking the state of the Car and which Decorators are applied. By removing a decorator you basically traverse the stack of applied decorators until the desired state and restore the Car object to that state (the preceded applying the removed decorator). Then you will need to re-apply the decorators that proceed thereafter. May not be the optimal solution, but it has the least impact on you current design.

0

精彩评论

暂无评论...
验证码 换一张
取 消