当前位置:金屋文档› 设计模式——抽象工厂模式(Abstract Factory Pattern)+ Spring相关源码

设计模式——抽象工厂模式(Abstract Factory Pattern)+ Spring相关源码

文章标签:: spring java 抽象工厂模式 后端 设计模式
文章摘要: 可以将对象的创建与使用代码分离,提供多个接口来创建相关类型的对象。

文章目录

  • 一、抽象工厂模式
  • 二、例子
    • 2.1 菜鸟教程例子
      • 2.1.1 定义被创建对象——形状
      • 2.1.2 定义被创建对象——颜色
      • 2.1.3 定义抽象工厂类
  • 三、其他设计模式

一、抽象工厂模式

类型: 创建型模式
目的: 可以将对象的创建使用代码分离,提供多个接口创建相关类型的对象

二、例子

2.1 菜鸟教程例子

2.1.1 定义被创建对象——形状

publicinterfaceShape{voiddraw();}
publicclassRectangleimplementsShape{@Overridepublicvoiddraw(){System.out.println("Inside Rectangle::draw() method.");}}
publicclassCircleimplementsShape{@Overridepublicvoiddraw(){System.out.println("Inside Circle::draw() method.");}}

2.1.2 定义被创建对象——颜色

publicinterfaceColor{voidfill();}
publicclassRedimplementsColor{@Overridepublicvoidfill(){System.out.println("Inside Red::fill() method.");}}
publicclassGreenimplementsColor{@Overridepublicvoidfill(){System.out.println("Inside Green::fill() method.");}}

2.1.3 定义抽象工厂类

该抽象工厂类可以创建形状颜色

publicabstractclassAbstractFactory{publicabstractColorgetColor(String color);publicabstractShapegetShape(String shape);}

形状工厂

publicclassShapeFactoryextendsAbstractFactory{@OverridepublicShapegetShape(String shapeType){if(shapeType ==null){returnnull;}if(shapeType.equalsIgnoreCase("CIRCLE")){returnnewCircle();}elseif(shapeType.equalsIgnoreCase("RECTANGLE")){returnnewRectangle();}returnnull;}@OverridepublicColorgetColor(String color){returnnull;}}

颜色工厂

publicclassColorFactoryextendsAbstractFactory{@OverridepublicShapegetShape(String shapeType){returnnull;}@OverridepublicColorgetColor(String color){if(color==null){returnnull;}if(color.equalsIgnoreCase("Red")){returnnewRed();}elseif(color.equalsIgnoreCase("Green")){returnnewGreen();}returnnull;}}

三、其他设计模式

创建型模式
结构型模式

  • 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码

行为型模式

  • 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
  • 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
  • 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
  • 4、设计模式——状态模式(State Pattern)
  • 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
  • 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
  • 7、设计模式——备忘录模式(Memento Pattern)
  • 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
  • 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
  • 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
  • 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码
相关文档
  • 设计模式

  • 源码

  • 抽象

相关文档推荐: