一、抽象工厂模式
类型: 创建型模式
目的: 可以将对象的创建与使用代码分离,提供多个接口来创建相关类型的对象。
二、例子
2.1 菜鸟教程例子
2.1.1 定义被创建对象——形状
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
2.1.2 定义被创建对象——颜色
public interface Color {
void fill();
}
public class Red implements Color {
@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("Inside Green::fill() method.");
}
}
2.1.3 定义抽象工厂类
该抽象工厂类可以创建形状 和 颜色。
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape);
}
形状工厂
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}
return null;
}
@Override
public Color getColor(String color) {
return null;
}
}
颜色工厂
public class ColorFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
return null;
}
@Override
public Color getColor(String color) {
if(color== null){
return null;
}
if(color.equalsIgnoreCase("Red")){
return new Red();
} else if(color.equalsIgnoreCase("Green")){
return new Green();
}
return null;
}
}
三、其他设计模式
创建型模式
结构型模式
行为型模式
- 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相关源码