一、简单工厂设计模式
实例化对象的时候不再使用 new Object()形式,可以根据用户的选择条件来实例化相关的类。对于客户端来说,去除了具体的类的依赖。只需要给出具体实例的描述给工厂,工厂就会自动返回具体的实例对象。
// 公共操作抽象类
public interface Operation {
double getResult(double numberA,double numberB) throws Exception;
}
// 加法计算实现类
public class Add implements Operation {
@Override
public double getResult(double numberA, double numberB) throws Exception {
return numberA + numberB;
}
}
// 简单工厂,根据字符串创建相应的对象
public class OperateFactory {
public static Operation createOperation(String name){
Operation operationObj = null;
switch (name) {
case "+":
operationObj = new Add();
break;
case "-":
operationObj = new Sub();
break;
case "*":
operationObj = new Mul();
break;
case "/":
operationObj = new Div();
break;
}
return operationObj;
}
}
// 使用
public class MainTest {
public static void main(String[] args) throws Exception {
Operation add = OperateFactory.createOperation("+");
System.out.println(add.getResult(1.0, 2.3));
}
}
二、工厂方法设计模式
父类定义了创建对象的接口,但是由子类来具体实现,工厂方法让类把实例化的动作推迟到了子类当中。
// 抽象类中定义了创建对象的接口
public abstract class JCacheOperationSourcePointcut
extends StaticMethodMatcherPointcut implements Serializable {
@Nullable
protected abstract JCacheOperationSource getCacheOperationSource();
// 子类实现创建对象的接口
public class BeanFactoryJCacheOperationSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
private JCacheOperationSource cacheOperationSource;
private final JCacheOperationSourcePointcut pointcut = new JCacheOperationSourcePointcut() {
@Override
protected JCacheOperationSource getCacheOperationSource() {
return cacheOperationSource;
}
};
public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) {
this.cacheOperationSource = cacheOperationSource;
}
// 使用
@Configuration
public class ProxyJCacheConfiguration extends AbstractJCacheConfiguration {
public BeanFactoryJCacheOperationSourceAdvisor cacheAdvisor() {
BeanFactoryJCacheOperationSourceAdvisor advisor = new BeanFactoryJCacheOperationSourceAdvisor();
advisor.setCacheOperationSource(cacheOperationSource());
advisor.setAdvice(cacheInterceptor());
if (this.enableCaching != null) {
advisor.setOrder(this.enableCaching.<Integer>getNumber("order"));
}
return advisor;
}
三、抽象工厂设计模式
抽象工厂模式:围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。
// 电脑工厂
public interface PcFactory {
Mouse getMouse();
Keyboard getKeyboard();
}
public interface Mouse {
void printBrand();
}
public class DellMouse implements Mouse {
@Override
public void printBrand() {
System.out.println("DELL MOUSE");
}
}
public interface Keyboard {
void printBrand();
}
public class DellKeyboard implements Keyboard {
@Override
public void printBrand() {
System.out.println("DELL KEYBOARD");
}
}
public class DellPcFatory implements PcFactory {
@Override
public Mouse getMouse() {
return new DellMouse();
}
@Override
public Keyboard getKeyboard() {
return new DellKeyboard();
}
}
// 使用
public class MainTests {
public static void main(String[] args) {
PcFactory pc = new DellPcFatory();
pc.getMouse().printBrand();
pc.getKeyboard().printBrand();
}
}