What is the difference between Factory and Strategy patterns?

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

    I may digress with Oscar in that his example of a Factory implementation is rather tightly coupled and very closed, no wonder your pick is Strategy pattern. A Factory implementation should not depend on any fixed number of specific classes being instantiated, For example:

    public Command getCommand( int operatingSystem ) {        
       return commandTable.get(operatingSystem); 
    }
    
    ...
    
    public class WindowsCommand implements Command {
        ...
        static {
            CommandTable.getInstance().registerCommand(WIN_COMMAND_ID, new WindowsCommand());
        }
    
    }
    

    I guess the most appropriate criteria to choose one or another is mostly the terms you employ to name your classes and methods, taking into account we all should tend to program to interfaces and not to classes and also focus on the goal: we aim to determine which code will execute on runtime. That said, we can achieve the goal by using any of both patterns.

提交回复
热议问题