What is the difference between Factory and Strategy patterns?

前端 未结 12 1454
执念已碎
执念已碎 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:04

    • The Factory ( method ) Pattern.

    Create concrete instances only. Different arguments may result in different objects. It depends on the logic etc.

    • The Strategy Pattern.

    Encapsulate the algorithm ( steps ) to perform an action. So you can change the strategy and use another algorithm.

    While both look like very similar, the purpose is rather different, one purpose is to create the other is to perform an action.

    So. If your Factory method is fixed, you may have it like this:

     public Command getCommand( int operatingSystem ) { 
          switch( operatingSystem ) { 
               case UNIX    :
               case LINUX   : return new UnixCommand();
               case WINDOWS : return new WindowsCommand();
               case OSX     : return new OSXCommand();
           }
      }
    

    But suppose your factory needs more advanced or dynamic creation. You may add to the factory method an strategy and change it without having to recompile, the strategy may change at runtime.

提交回复
热议问题