常见的26中设计模式是哪些?请详细说明并写出代码
时间: 2024-05-03 13:23:00 浏览: 16
常见的26种设计模式包括:
1. 工厂模式(Factory Pattern)
2. 抽象工厂模式(Abstract Factory Pattern)
3. 单例模式(Singleton Pattern)
4. 建造者模式(Builder Pattern)
5. 原型模式(Prototype Pattern)
6. 代理模式(Proxy Pattern)
7. 适配器模式(Adapter Pattern)
8. 桥接模式(Bridge Pattern)
9. 装饰器模式(Decorator Pattern)
10. 外观模式(Facade Pattern)
11. 组合模式(Composite Pattern)
12. 享元模式(Flyweight Pattern)
13. 策略模式(Strategy Pattern)
14. 模板方法模式(Template Method Pattern)
15. 观察者模式(Observer Pattern)
16. 迭代器模式(Iterator Pattern)
17. 职责链模式(Chain of Responsibility Pattern)
18. 命令模式(Command Pattern)
19. 访问者模式(Visitor Pattern)
20. 备忘录模式(Memento Pattern)
21. 状态模式(State Pattern)
22. 解释器模式(Interpreter Pattern)
23. 中介者模式(Mediator Pattern)
24. 享元模式(Flyweight Pattern)
25. 代理模式(Proxy Pattern)
26. 外观模式(Facade Pattern)
下面以工厂模式和单例模式为例进行详细说明和代码演示。
工厂模式(Factory Pattern)
工厂模式是一种创建型模式,它提供了一种创建对象的方式,而无需指定具体的类。在工厂模式中,我们定义一个接口或抽象类作为创建对象的工厂,而具体的对象创建则由实现该接口的子类来完成。
代码演示:
```java
// 工厂类接口
public interface ShapeFactory {
Shape createShape();
}
// 具体工厂类1
public class CircleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Circle();
}
}
// 具体工厂类2
public class RectangleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Rectangle();
}
}
// 抽象产品类
public abstract class Shape {
public abstract void draw();
}
// 具体产品类1
public class Circle extends Shape {
@Override
public void draw() {
System.out.println("Draw a circle.");
}
}
// 具体产品类2
public class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Draw a rectangle.");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
ShapeFactory factory1 = new CircleFactory();
Shape circle = factory1.createShape();
circle.draw();
ShapeFactory factory2 = new RectangleFactory();
Shape rectangle = factory2.createShape();
rectangle.draw();
}
}
```
单例模式(Singleton Pattern)
单例模式是一种创建型模式,它保证一个类只有一个实例,并提供了访问该实例的全局访问点。
代码演示:
```java
// 单例模式实现
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // true
}
}
```