例子:
/** * 运算类:有一个抽象方法 */ public abstract class Operation { public double number1; public double number2; public abstract double result(); }
/** * 加法类,继承运算类并且重写父类方法 */ public class OperationAdd extends Operation { @Override public double result() { return number1 + number2; } }
/** * 减法类,继承运算类并且重写父类方法 */ public class OperationSub extends Operation { @Override public double result() { return number1 - number2; } }
/** * 创建一个简单工厂 */ public class OpreationFactory { public static Operation createOperate(String operate){ Operation operation = null; switch (operate){ case "+": operation = new OperationAdd(); break; case "-": operation = new OperationSub(); break; default: System.out.println("您输入的运算符有误!"); } return operation; } }
/** * 测试类 */ public class Calculator { public static void main(String[] args) { Operation operation; String operator; operator = "-"; operation = OpreationFactory.createOperate(operator); operation.number1 = 10; operation.number2 = 8; System.out.println(operation.result()); } }
优缺点:
例子:还是上面的运算例子,如果需要添加一个乘法运算的话,除了要添加一个乘法类继承运算类,还需要修改工厂代码添加一个判断,所以 简单工厂模式违背了开闭原则 。使用工厂模式的话只需要添加一个乘法类继承运算类以及添加一个乘法工厂实现工厂接口就可以了,完美的遵循开闭原则,代码如下:
/** * 工厂方法 */ public interface IFactory { Operation createOperation(); }
/** * 加法工厂,实现了工厂方法接口 */ public class AddFactory implements IFactory { @Override public Operation createOperation() { return new OperationAdd(); //该类见上面简单工厂方法 } } /** * 减法工厂,实现了工厂方法接口 */ public class SubFactory implements IFactory { @Override public Operation createOperation() { return new OperationSub(); //该类见上面简单工厂方法 } } /** * 乘法工厂,实现了工厂方法接口 */ public class MultiFactory implements IFactory { @Override public Operation createOperation() { return new OperationMulti(); } }
/** * 乘法类,继承运算类并且重写父类方法 */ public class OperationMulti extends Operation{ @Override public double result() { return number1 * number2; } }
/** * 测试类 */ public class Calculator { public static void main(String[] args) { Operation operation; IFactory factory = new MultiFactory(); operation = factory.createOperation(); operation.number1 = 2; operation.number2 = 3; System.out.println(operation.result()); } }
优缺点:
优缺点: