工厂方法模式
1.工厂方法模式实现
2.什么是工厂:就比如现实中的工厂,就是用来生产东西的地方。比如在java中工厂可以生产对象,这样就避免我们在客户端new 过多的对象。上面每个计算类对应一个工厂类。
3.工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
4.工厂方法克服了简单工厂违背开放——封闭原则的缺点,又保持了封装对象创建过程的优点。
5.代码如下
运算类接口
package Factory;
public class Client {
public static void main(String[] args) throws Exception {
IFactory operFactory = new AddFactory();
Operation add = operFactory.CreateOperation();
System.out.println(add.getResult(1.0, 1.0));
}
}
加法运算类
package Factory;
public class OperationAdd implements Operation{
@Override
public double getResult(double numberA, double numberB) throws Exception {
return numberA + numberB;
}
}
减法运算类
package Factory;
public class OperationSub implements Operation{
@Override
public double getResult(double numberA, double numberB) throws Exception {
return numberA - numberB;
}
}
乘法运算类
package Factory;
public class OperationMul implements Operation{
@Override
public double getResult(double numberA, double numberB) throws Exception {
return numberA * numberB;
}
}
除法运算类
package Factory;
public class OperationDiv implements Operation{
@Override
public double getResult(double numberA, double numberB) throws Exception {
if (numberB == 0) {
throw new Exception(“除数不能为0!”);
}
return numberA / numberB;
}
}
工厂接口
package Factory;
public interface IFactory {
public Operation CreateOperation();
}
加法工厂
package Factory;
public class AddFactory implements IFactory{
@Override
public Operation CreateOperation() {
return new OperationAdd();
}
}
减法工厂
package Factory;
public class SubFactory implements IFactory{
@Override
public Operation CreateOperation() {
return new OperationSub();
}
}
乘法工厂
package Factory;
public class MulFactory implements IFactory{
@Override
public Operation CreateOperation() {
return new OperationMul();
}
}
除法工厂
package Factory;
public class DivFactory implements IFactory{
@Override
public Operation CreateOperation() {
return new OperationDiv();
}
}
客户端类
package Factory;
public class Client {
public static void main(String[] args) throws Exception {
IFactory operFactory = new AddFactory();
Operation add = operFactory.CreateOperation();
System.out.println(add.getResult(1.0, 1.0));
}
}
结果
2.0