Gof23 设计模式,也叫Gang of Four(GoF)设计模式,是由四位设计模式大师(Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides)撰写的一本书——《设计模式:可复用面向对象软件的基础》所引起的热潮,它提出了23种软件设计模式,这些模式可以帮助开发人员更好地理解、设计和实现一个软件系统。
这23种模式分为三类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)和行为型模式(Behavioral Patterns)。
创建型模式:
1. 工厂方法模式(Factory Method)
2. 抽象工厂模式(Abstract Factory)
3. 单例模式(Singleton)
4. 建造者模式(Builder)
5. 原型模式(Prototype)
结构型模式:
1. 适配器模式(Adapter)
2. 桥接模式(Bridge)
3. 组合模式(Composite)
4. 装饰器模式(Decorator)
5. 外观模式(Facade)
6. 享元模式(Flyweight)
7. 代理模式(Proxy)
行为型模式:
1. 责任链模式(Chain of Responsibility)
2. 命令模式(Command)
3. 解释器模式(Interpreter)
4. 迭代器模式(Iterator)
5. 中介者模式(Mediator)
6. 备忘录模式(Memento)
7. 观察者模式(Observer)
8. 状态模式(State)
9. 策略模式(Strategy)
10. 模板方法模式(Template Method)
11. 访问者模式(Visitor)
以下是各个模式的代码 Demo:
工厂方法模式:
public interface FruitFactory {
Fruit getFruit();
}
public class AppleFactory implements FruitFactory {
@Override
public Fruit getFruit() {
return new Apple();
}
}
public class OrangeFactory implements FruitFactory {
@Override
public Fruit getFruit() {
return new Orange();
}
}
抽象工厂模式:
public interface FruitFactory {
Fruit getFruit();
Juice getJuice();
}
public class AppleFactory implements FruitFactory {
@Override
public Fruit getFruit() {
return new Apple();
}
@Override
public Juice getJuice() {
return new AppleJuice();
}
}
public class OrangeFactory implements FruitFactory {
@Override
public Fruit getFruit() {
return new Orange();
}
@Override
public Juice getJuice() {
return new OrangeJuice();
}
}
单例模式:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
建造者模式:
public class ComputerBuilder {
private Computer computer;
public ComputerBuilder() {
this.computer = new Computer();
}
public ComputerBuilder setCpu(String cpu) {
this.computer.setCpu(cpu);
return this;
}
public ComputerBuilder setRam(String ram) {
this.computer.setRam(ram);
return this;
}
public ComputerBuilder setStorage(String storage) {
this.computer.setStorage(storage);
return this;
}
public Computer build() {
return this.computer;
}
}
原型模式:
public class Prototype implements Cloneable {
private String name;
public Prototype(String name) {
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}