场景: 没有场景,不要new, 学习spring

1.工厂模式

  1. package com.example.demo.pattern.factory;
  2. /**
  3. * @author chenchao
  4. * @date 2021/11/8
  5. */
  6. public class FactoryPatternDemo {
  7. public static void main(String[] args) {
  8. Product product = ProductFactory.create();
  9. product.execute();
  10. }
  11. public interface Product {
  12. void execute();
  13. }
  14. public static class ProductImpl implements Product {
  15. @Override
  16. public void execute() {
  17. System.out.print("产品1的功能实现");
  18. }
  19. }
  20. public static class ProductFactory {
  21. public static Product create() {
  22. return new ProductImpl();
  23. }
  24. }
  25. }

2.说明

核心:工厂模式的核心思想,其实就是不要自己在代码里手动new一个实现类对象出来,因为那样的话,调用方就不是面向接口编程了,你还得自己去care实现了。

我们设想一下,假设有N个client都new了一个ProductImpl出来,结果,到了后面某一天,你要把ProductImpl换成ProductNewImpl了,完全换一套实现逻辑,这个时候就完蛋了。你需要在N个client里,都修改new ProductImpl()这个方法,简直是一场灾难啊。尤其如果调用你的类的是别人呢?别人还得来care这个事情?