场景: 没有场景,不要new, 学习spring
1.工厂模式
package com.example.demo.pattern.factory;
/**
* @author chenchao
* @date 2021/11/8
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
Product product = ProductFactory.create();
product.execute();
}
public interface Product {
void execute();
}
public static class ProductImpl implements Product {
@Override
public void execute() {
System.out.print("产品1的功能实现");
}
}
public static class ProductFactory {
public static Product create() {
return new ProductImpl();
}
}
}
2.说明
核心:工厂模式的核心思想,其实就是不要自己在代码里手动new一个实现类对象出来,因为那样的话,调用方就不是面向接口编程了,你还得自己去care实现了。
我们设想一下,假设有N个client都new了一个ProductImpl出来,结果,到了后面某一天,你要把ProductImpl换成ProductNewImpl了,完全换一套实现逻辑,这个时候就完蛋了。你需要在N个client里,都修改new ProductImpl()这个方法,简直是一场灾难啊。尤其如果调用你的类的是别人呢?别人还得来care这个事情?