Strategy Pattern V/S Decorator Pattern

后端 未结 7 1302
星月不相逢
星月不相逢 2021-01-29 20:06

I just came across two patterns.

  1. Strategy Pattern

  2. Decorator

Strategy Pattern :-

Strategy pattern

7条回答
  •  醉梦人生
    2021-01-29 20:48

    The strategy is pattern is used to "encapsulate what changes". It allows you to define algorithms that can be interchanged at runtime. For example (example taken from Head First Design Patterns):

    Say you have a a duck simulator. You want to make your duck objects fly. You could use inheritance for this but it gets messy quickly. Some ducks can't fly (e.g. rubber ducks). The way to do this is to encapsulate what changes i.e. the fly behaviour into its own class that implement IFlybehaviour for example. You can then use composition instead of inheritance and inject the IFlybehaviour into your duck objects. You could also then have a method that sets this fly behaviour so the fly behaviour can be changed at runtime. This is essentially the strategy pattern.

    The decorator pattern is used to add functionality to an object at runtime. It allows you to wrap objects within objects. Decorators must have the same supertype as the objects they decorate. This allows you to call a method on the "outmost wrapper" and you can then chain call this same method down through the layers of decorators. It is basically a more flexible approach than subclassing.

    As to which ones you choose depends on the problem you want to solve. Do you want to have a family of algorthims that are interchangeable at runtime or do you want to dynamically add more functionality to an object at run time?

    The book "Head first design patterns" explains this quite well (probably much better than me) IMO so it is worth a read if you get chance.

    Good luck.

提交回复
热议问题