專門負責將大量有共同接口的類實例化,工廠模式能夠動態的決定將哪個類進行實例化,沒必要事先知道要實例化那一個類。算法
簡單工廠模式,又稱爲靜態工廠方法模式。ide
工廠方法模式,又稱爲多態性工廠模式。工具
抽象工廠模式,又稱爲工具箱模式。測試
package main; public interface Operation { int operate(int num1, int num2); }
package main.Impl; import main.Operation; public class AddOperation implements Operation { @Override public int operate(int num1, int num2) { return num1 + num2; } }
package main.Impl; import main.Operation; public class MultiOperation implements Operation { @Override public int operate(int num1, int num2) { return num1 * num2; } }
package main; public enum OperationEnum { Add, MINUS, MULTI, DIVIDE; }
public class FactoryUtils { public static Operation createOperation(OperationEnum operationEnum){ switch (operationEnum){ case Add: return new AddOperation(); case MULTI: return new MultiOperation(); } return null; } }
public class OperationTest { public static void main(String[] args){ int num1 = 100; int num2 = 200; Operation addOperation = FactoryUtils.createOperation(OperationEnum.Add); int addResult = addOperation.operate(num1, num2); System.out.println("args = [" + addResult + "]"); Operation multiOperation = FactoryUtils.createOperation(OperationEnum.MULTI); int multiResult = multiOperation.operate(num1, num2); System.out.println("args = [" + multiResult + "]"); } }
策略模式定義了算法家族,分別封裝起來,讓他們之間能夠相互替換;此模式讓算法的變化,不會影響到使用算法的客戶。spa
抽象策略,定義個抽象類或接口,並個給出具體策略的接口。3d
具體策略,抽象策略的實現類,具體實現了相關的算法和行爲。code
環境類,持有一個策略的引用。對象
package main; public interface OperationStrategy { int operate(int num1, int num2); }
package main.Impl; import main.OperationStrategy; public class AddStrategy implements OperationStrategy { @Override public int operate(int num1, int num2) { return num1 + num2; } }
package main.Impl; import main.OperationStrategy; public class SubstractionStrategy implements OperationStrategy { @Override public int operate(int num1, int num2) { return num1 - num2; } }
package test; import main.Impl.AddStrategy; import main.Impl.OperationContext; import main.Impl.SubstractionStrategy; public class StrategyTest { public static void main(String[] args){ OperationContext addContext = new OperationContext(new AddStrategy()); addContext.executeOperate(100, 200); OperationContext subContext = new OperationContext(new SubstractionStrategy()); subContext.executeOperate(100, 200); } }