What is the difference between Factory and Strategy patterns?

前端 未结 12 1502
执念已碎
执念已碎 2020-12-02 04:53

Can any one explain the difference between factory and strategy patterns?

For me both are looking same other than an extra factory class (which create an object of

12条回答
  •  情话喂你
    2020-12-02 05:17

    Factory (and FactoryMethod returned by Factory):

    1. Creational pattern
    2. Based on inheritance
    3. Factory returns a Factory Method (interface) which in turn returns Concrete Object
    4. You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
    5. Client always access interface only and you can hide object creation details in Factory method

    Have a look at this wikipedia article and javarevisited article

    Strategy pattern:

    1. It's a behavioural pattern
    2. It's based on delegation
    3. It changes guts of the object by modifying method behaviour
    4. It's used to switch between family of algorithms
    5. It changes the behaviour of the object at run time

    Example:

    You can configure Discount strategy for a particular item ( AirFare ticket or ShoppingCart item). In this example, you will offer 25% discount to an item during July - December and No discount on the item during Jaunary - June.

    Related posts:

    Real World Example of the Strategy Pattern

    Design Patterns: Factory vs Factory method vs Abstract Factory

提交回复
热议问题