简单工厂
代码:
public class FactoryTest {
public static void main(String[] args) {
Operation operate = OperationFactory.createOperate("+");
operate.NumberA = 3;
operate.NumberB = 4;
System.out.println(operate.GetReuslt());
}
}
public abstract class Operation {
int NumberA;
int NumberB;
public abstract int GetReuslt();
}
public class OperationAdd extends Operation {
@Override
public int GetReuslt() {
return NumberA + NumberB;
}
}
public class OperationDiv extends Operation{
@Override
public int GetReuslt() {
return NumberA - NumberB;
}
}
public class OperationFactory {
public static Operation createOperate(String operation){
Operation factory = null;
switch (operation){
case "+" :
factory = new OperationAdd();
break;
case "-":
factory = new OperationDiv();
break;
}
return factory;
}
}
工厂模式
工厂模式与简单工厂的区别:
简单工厂模式最大的优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态 实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
简单工厂违反了开闭原则
工厂模式的缺点:新增一个种类,都需要新增一个工厂和一个产品,使用反射可以优化
工厂模式结构图
public class FactoryTest {
public static void main(String[] args) {
IFactory operFactory = new AddFactory();
Operation operation = operFactory.createOperation();
operation.NumberA = 3;
operation.NumberB = 4;
System.out.println(operation.GetReuslt());
}
}
//工厂抽象类
public interface IFactory {
Operation createOperation();
}
//加法工厂
public class AddFactory implements IFactory{
@Override
public Operation createOperation() {
return new OperationAdd();
}
}
//减法工厂
public class DivFactory implements IFactory {
@Override
public Operation createOperation() {
return new OperationDiv();
}
}
//运算抽象类
public abstract class Operation {
public int NumberA;
public int NumberB;
public abstract int GetReuslt();
}
//加法运算类
public class OperationAdd extends Operation {
@Override
public int GetReuslt() {
return NumberA + NumberB;
}
}
//减法运算类
public class OperationDiv extends Operation{
@Override
public int GetReuslt() {
return NumberA - NumberB;
}
}
抽象工厂:
概念:提供一个创建一系列相关或相互依赖对象的接口,而无需指定他们具体的类
我之前不理解的点:抽象工厂相对于工厂模式而言,工厂模式对多个产品进行操作的时候,代码非常冗余,抽象工厂解决的就是产品族。相较于之前的工厂模式,抽象工厂只是多了一个AbstactFactory接口,让不同的工厂实现他。
抽象工厂缺点:新增抽象工厂功能时,要改动接口,以及所有实现类,改动非常大
不如直接使用简单工厂,使用简单工厂的缺点是新增一种工厂代码量又会增多。