抽象工厂模式的结构图抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。
工厂模式中的角色:
- Product:抽象产品类。
- ConcreteProduct:具体产品类,实现 Product 接口。
- Product2:抽象产品类2。
- ConcreteProduct2:具体产品类2,实现 Product2 接口。
- Factory:抽象工厂类,该方法返回一个 Product 类型的对象。
- ConcreteFactory:具体工厂类,返回 ConcreteProduct 实例。
抽象工厂模式的简单实现
(1) 抽象产品类
public abstract class Comparator {
private double[] data;
public void setData(double ...data) {
this.data = data;
}
public double[] getData() {
return data;
}
public abstract double getResult();
}
(2) 具体产品类
public class MaxComparator extends Comparator {
@Override
public double getResult() {
double max = Double.NEGATIVE_INFINITY;
for (int i = 0, length = getData().length; i < length; i++) {
max = Math.max(max, getData()[i]);
}
return max;
}
}
public class MinComparator extends Comparator {
@Override
public double getResult() {
double min = Double.POSITIVE_INFINITY;
for (int i = 0, length = getData().length; i < length; i++) {
min = Math.min(min, getData()[i]);
}
return min;
}
}
(3) 抽象工厂
public abstract class IFactory {
public abstract <T extends Operation> T createOperate(Class<T> clz);
public abstract <T extends Comparator> T createCompare(Class<T> clz);
}
(4) 具体工厂
public class Factory extends IFactory {
@Override
public <T extends Operation> T createOperate(Class<T> clz) {
Operation operation = null;
String className = clz.getName();
try {
operation = (Operation) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return (T)operation;
}
@Override
public <T extends Comparator> T createCompare(Class<T> clz) {
Comparator comparator = null;
String className = clz.getName();
try {
comparator = (Comparator) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return (T)comparator;
}
}
(5) 客户端调用
public class Calculator {
public static void main(String[] args) {
IFactory iOperationFactory = new Factory();
Operation operation = iOperationFactory.createOperate(OperationAdd.class);
operation.setX(10);
operation.setY(20);
Comparator comparator = iOperationFactory.createCompare(MinComparator.class);
comparator.setData(10, 15, 5);
try {
System.out.print("结果:" + operation.getResult());
System.out.print("结果:" + comparator.getResult());
} catch (Exception e) {
e.printStackTrace();
}
}
}
工厂方法和抽象工厂
工厂模式是用来创建同一个产品的不同类型的,但是抽象工厂模式是用来创建不同类的产品。
网友评论