一、概念
工厂方法模式(FACTORY METHOD)是一种常用的类创建型设计模式,此模式的核心精神是封装类中变化的部分,提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。它的核心结构有四个角色,分别是抽象工厂;具体工厂;抽象产品;具体产品。
抽象工厂(Creator)角色:是工厂方法模式的核心,与应用程序无关。任何在模式中创建的对象的工厂类必须实现这个接口。
具体工厂(Concrete Creator)角色:这是实现抽象工厂接口的具体工厂类,包含与应用程序密切相关的逻辑,并且受到应用程序调用以创建产品对象。在上图中有两个这样的角色:BulbCreator与TubeCreator。
抽象产品(Product)角色:工厂方法模式所创建的对象的超类型,也就是产品对象的共同父类或共同拥有的接口。在上图中,这个角色是Light。
具体产品(Concrete Product)角色:这个角色实现了抽象产品角色所定义的接口。某具体产品有专
门的具体工厂创建,它们之间往往一一对应。
二、代码实现
需求:显示两个数的计算(加、减、乘除、次方、方根)
抽象工厂:
public interface IFactory { public Operation createOperation(String operate); }
具体工厂:
public class OperationFactory { public static Operation createOperate(String operate) { Operation oper = null; IFactory factory = null; switch (operate) { case "+": case "-": case "*": case "/": factory = new FactoryBasic(); break; case "pow": case "log": factory=new FactoryAdvanced(); } oper = factory.createOperation(operate); return oper; } } public class FactoryBasic implements IFactory{ @Override public Operation createOperation(String operate) { Operation oper = null; switch (operate) { case "+": oper = new Add(); break; case "-": oper = new Sub(); break; case "*": oper = new Mul(); break; case "/": oper = new Div(); break; } return oper; } } public class FactoryAdvanced implements IFactory{ @Override public Operation createOperation(String operate) { Operation oper = null; switch (operate) { case "pow": oper = new Pow(); break; case "log": oper = new Log(); break; } return oper; } }
抽象产品:
public abstract class Operation { public abstract double getResult(double numberA,double numberB); }
具体产品:
public class Add extends Operation { @Override public double getResult(double numberA, double numberB) { return numberA+numberB; } } public class Div extends Operation { @Override public double getResult(double numberA, double numberB) { if (numberB==0) { throw new ArithmeticException(); } return numberA/numberB; } } public class Log extends Operation { @Override public double getResult(double numberA, double numberB) { return Math.log(numberB)/Math.log(numberA); } } public class Mul extends Operation { @Override public double getResult(double numberA, double numberB) { return numberA*numberB; } } public class Pow extends Operation { @Override public double getResult(double numberA, double numberB) { return Math.pow(numberA,numberB); } } public class Sub extends Operation { @Override public double getResult(double numberA, double numberB) { return numberA-numberB; } }
测试:
public static void main(String[] args) { Operation log = OperationFactory.createOperate("pow"); System.out.println(log.getResult(10, 2)); }