营销型 网站 品牌网站seo快速排名
目录
什么是设计模式
设计模式的分类
创建型模式
结构型模式
行为型模式
其他常用模式
总结与最佳实践
什么是设计模式
基本概念
设计模式就像是建筑师的图纸,是解决软件设计中常见问题的经过验证的最佳实践。
简单理解:
- 就像做菜有固定的步骤和搭配
- 写代码也有一些"套路"和"模板"
- 这些"套路"就是设计模式
GoF的23种设计模式
1995年,四位作者(Gang of Four,简称GoF)总结了23种经典设计模式,这是软件设计的经典之作。
设计模式的分类
类型 | 数量 | 目的 | 模式列表 |
---|---|---|---|
创建型 | 5个 | 如何创建对象 | 单例、工厂方法、抽象工厂、建造者、原型 |
结构型 | 7个 | 如何组装对象 | 适配器、桥接、组合、装饰器、外观、享元、代理 |
行为型 | 11个 | 对象间如何协作 | 责任链、命令、解释器、迭代器、中介者、备忘录、观察者、状态、策略、模板方法、访问者 |
创建型模式
创建型模式主要解决"如何优雅地创建对象"的问题。
1. 单例模式 (Singleton)
什么时候用?
确保一个类只有一个实例,比如数据库连接池、日志记录器。
生活例子
一个公司只能有一个CEO。
代码实现
public class Singleton {private static final Singleton INSTANCE = new Singleton();private Singleton() {}public static Singleton getInstance() {return INSTANCE;}public void doSomething() {System.out.println("单例在工作...");}
}
2. 工厂方法模式 (Factory Method)
什么时候用?
需要创建产品,但具体创建哪种产品由子类决定。
生活例子
不同品牌的汽车工厂,都能造车,但造出来的车不一样。
代码实现
// 产品接口
interface Product {void use();
}// 具体产品
class ConcreteProductA implements Product {@Overridepublic void use() {System.out.println("使用产品A");}
}class ConcreteProductB implements Product {@Overridepublic void use() {System.out.println("使用产品B");}
}// 工厂接口
abstract class Factory {public abstract Product createProduct();
}// 具体工厂
class FactoryA extends Factory {@Overridepublic Product createProduct() {return new ConcreteProductA();}
}class FactoryB extends Factory {@Overridepublic Product createProduct() {return new ConcreteProductB();}
}
3. 抽象工厂模式 (Abstract Factory)
什么时候用?
需要创建一系列相关的产品。
生活例子
家具工厂,既能生产现代风格的桌椅,也能生产古典风格的桌椅。
代码实现
// 产品接口
interface Chair { void sit(); }
interface Table { void put(); }// 现代风格产品
class ModernChair implements Chair {@Overridepublic void sit() { System.out.println("坐在现代椅子上"); }
}class ModernTable implements Table {@Overridepublic void put() { System.out.println("在现代桌子上放东西"); }
}// 古典风格产品
class ClassicChair implements Chair {@Overridepublic void sit() { System.out.println("坐在古典椅子上"); }
}class ClassicTable implements Table {@Overridepublic void put() { System.out.println("在古典桌子上放东西"); }
}// 抽象工厂
interface FurnitureFactory {Chair createChair();Table createTable();
}// 具体工厂
class ModernFurnitureFactory implements FurnitureFactory {@Overridepublic Chair createChair() { return new ModernChair(); }@Overridepublic Table createTable() { return new ModernTable(); }
}class ClassicFurnitureFactory implements FurnitureFactory {@Overridepublic Chair createChair() { return new ClassicChair(); }@Overridepublic Table createTable() { return new ClassicTable(); }
}
4. 建造者模式 (Builder)
什么时候用?
创建复杂对象,且有很多可选参数。
生活例子
去肯德基点餐,选择汉堡、饮料、薯条组成套餐。
代码实现
public class Computer {private String cpu;private String memory;private String storage;private Computer(Builder builder) {this.cpu = builder.cpu;this.memory = builder.memory;this.storage = builder.storage;}public static class Builder {private String cpu;private String memory;private String storage;public Builder setCpu(String cpu) {this.cpu = cpu;return this;}public Builder setMemory(String memory) {this.memory = memory;return this;}public Builder setStorage(String storage) {this.storage = storage;return this;}public Computer build() {return new Computer(this);}}@Overridepublic String toString() {return String.format("电脑: CPU=%s, 内存=%s, 存储=%s", cpu, memory, storage);}
}
5. 原型模式 (Prototype)
什么时候用?
创建对象成本较高,通过克隆现有对象来创建新对象。
生活例子
复印文件,不用重新写,直接复印一份。
代码实现
// 原型接口
interface Prototype extends Cloneable {Prototype clone();
}// 具体原型
class ConcretePrototype implements Prototype {private String name;private int age;public ConcretePrototype(String name, int age) {this.name = name;this.age = age;}@Overridepublic Prototype clone() {try {return (Prototype) super.clone();} catch (CloneNotSupportedException e) {return new ConcretePrototype(this.name, this.age);}}@Overridepublic String toString() {return "ConcretePrototype{name='" + name + "', age=" + age + "}";}
}// 使用示例
public class PrototypeTest {public static void main(String[] args) {ConcretePrototype original = new ConcretePrototype("张三", 25);ConcretePrototype copy = (ConcretePrototype) original.clone();System.out.println("原型: " + original);System.out.println("克隆: " + copy);}
}
结构型模式
结构型模式主要解决"如何优雅地组合对象"的问题。
1. 适配器模式 (Adapter)
什么时候用?
接口不兼容,需要转换。
生活例子
电源适配器,把220V转换为5V。
代码实现
// 目标接口
interface Target {void request();
}// 被适配者
class Adaptee {public void specificRequest() {System.out.println("特殊请求");}
}// 适配器
class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;}