设计模式详解
约 533 字大约 2 分钟
设计模式
2024-03-02
设计模式的分类
根据Design Patterns - Elements of Reusable Object-Oriented Software(中文译名:设计模式 - 可复用的面向对象软件元素)一书,总体来说设计模式分为三大类:
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
单例模式
// 懒汉式
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
return instance;
}
}
}
//饿汉式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
// 双重检查
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;
}
}
}
}
}
工厂模式(Factory Pattern)
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
}
if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
生成器模式
// 生成器模式
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public void draw() {
circle.draw();
rectangle.draw();
square.draw();
}
public void setCircle(Shape circle) {
this.circle = circle;
}
public void setRectangle(Shape rectangle) {
this.rectangle = rectangle;
}
public void setSquare(Shape square) {
this.square = square;
}
}
原型模式
//原型模式
public class ShapeCache {
private static Map<String, Shape> shapeMap = new HashMap<>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return cachedShape.clone();
}
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(), circle);
Rectangle rectangle = new Rectangle();
rectangle.setId("2");
shapeMap.put(rectangle.getId(), rectangle);
Square square = new Square();
square.setId("3");
shapeMap.put(square.getId(), square);
}
}
适配器模式
public class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw() {
decoratedShape.draw();
}
}
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
decoratedShape.setBorderColor("Red");
}
public void setBorderColor(String borderColor) {
decoratedShape.setBorderColor(borderColor);
}
}