Java 和 Kotlin 实现 23 种设计模式:从理论到实践

打印 上一主题 下一主题

主题 957|帖子 957|积分 2871

设计模式是软件开发中办理常见问题的经典办理方案模板。它们帮助开发者编写可维护、可扩展和可重用的代码。本文详细介绍了 23 种经典设计模式,包括创建型、结构型和举动型模式,并提供了 JavaKotlin 的完整实现示例。无论你是初学者照旧有履历的开发者,本文都能帮助你深入理解设计模式的核心思想,并将其应用到实际项目中。
Java 和 Kotlin 实现 23 种设计模式

设计模式是软件开发中常见问题的办理方案模板。它们帮助开发者编写可维护、可扩展和可重用的代码。本文将详细介绍 23 种经典设计模式,并提供 Java 和 Kotlin 的实现示例。
1. 创建型模式

1.1 单例模式 (Singleton)

目标: 确保一个类只有一个实例,并提供全局访问点。
Java 实现:
  1. public class Singleton {
  2.     private static Singleton instance;
  3.     private Singleton() {}
  4.     public static Singleton getInstance() {
  5.         if (instance == null) {
  6.             instance = new Singleton();
  7.         }
  8.         return instance;
  9.     }
  10. }
复制代码
Kotlin 实现:
  1. object Singleton
复制代码
1.2 工厂方法模式 (Factory Method)

目标: 定义一个创建对象的接口,但让子类决定实例化哪个类。
Java 实现:
  1. interface Product {
  2.     void use();
  3. }
  4. class ConcreteProduct implements Product {
  5.     @Override
  6.     public void use() {
  7.         System.out.println("Using ConcreteProduct");
  8.     }
  9. }
  10. abstract class Creator {
  11.     public abstract Product factoryMethod();
  12. }
  13. class ConcreteCreator extends Creator {
  14.     @Override
  15.     public Product factoryMethod() {
  16.         return new ConcreteProduct();
  17.     }
  18. }
复制代码
Kotlin 实现:
  1. interface Product {
  2.     fun use()
  3. }
  4. class ConcreteProduct : Product {
  5.     override fun use() {
  6.         println("Using ConcreteProduct")
  7.     }
  8. }
  9. abstract class Creator {
  10.     abstract fun factoryMethod(): Product
  11. }
  12. class ConcreteCreator : Creator() {
  13.     override fun factoryMethod(): Product {
  14.         return ConcreteProduct()
  15.     }
  16. }
复制代码
1.3 抽象工厂模式 (Abstract Factory)

目标: 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
Java 实现:
  1. interface AbstractFactory {
  2.     ProductA createProductA();
  3.     ProductB createProductB();
  4. }
  5. class ConcreteFactory1 implements AbstractFactory {
  6.     @Override
  7.     public ProductA createProductA() {
  8.         return new ConcreteProductA1();
  9.     }
  10.     @Override
  11.     public ProductB createProductB() {
  12.         return new ConcreteProductB1();
  13.     }
  14. }
  15. class ConcreteFactory2 implements AbstractFactory {
  16.     @Override
  17.     public ProductA createProductA() {
  18.         return new ConcreteProductA2();
  19.     }
  20.     @Override
  21.     public ProductB createProductB() {
  22.         return new ConcreteProductB2();
  23.     }
  24. }
复制代码
Kotlin 实现:
  1. interface AbstractFactory {
  2.     fun createProductA(): ProductA
  3.     fun createProductB(): ProductB
  4. }
  5. class ConcreteFactory1 : AbstractFactory {
  6.     override fun createProductA(): ProductA {
  7.         return ConcreteProductA1()
  8.     }
  9.     override fun createProductB(): ProductB {
  10.         return ConcreteProductB1()
  11.     }
  12. }
  13. class ConcreteFactory2 : AbstractFactory {
  14.     override fun createProductA(): ProductA {
  15.         return ConcreteProductA2()
  16.     }
  17.     override fun createProductB(): ProductB {
  18.         return ConcreteProductB2()
  19.     }
  20. }
复制代码
1.4 建造者模式 (Builder)

目标: 将一个复杂对象的构建与其体现分离,使得同样的构建过程可以创建不同的体现。
Java 实现:
  1. class Product {
  2.     private String partA;
  3.     private String partB;
  4.     public void setPartA(String partA) {
  5.         this.partA = partA;
  6.     }
  7.     public void setPartB(String partB) {
  8.         this.partB = partB;
  9.     }
  10.     @Override
  11.     public String toString() {
  12.         return "Product{partA='" + partA + "', partB='" + partB + "'}";
  13.     }
  14. }
  15. interface Builder {
  16.     void buildPartA();
  17.     void buildPartB();
  18.     Product getResult();
  19. }
  20. class ConcreteBuilder implements Builder {
  21.     private Product product = new Product();
  22.     @Override
  23.     public void buildPartA() {
  24.         product.setPartA("PartA");
  25.     }
  26.     @Override
  27.     public void buildPartB() {
  28.         product.setPartB("PartB");
  29.     }
  30.     @Override
  31.     public Product getResult() {
  32.         return product;
  33.     }
  34. }
  35. class Director {
  36.     private Builder builder;
  37.     public Director(Builder builder) {
  38.         this.builder = builder;
  39.     }
  40.     public void construct() {
  41.         builder.buildPartA();
  42.         builder.buildPartB();
  43.     }
  44. }
复制代码
Kotlin 实现:
  1. class Product {
  2.     var partA: String = ""
  3.     var partB: String = ""
  4.     override fun toString(): String {
  5.         return "Product(partA='$partA', partB='$partB')"
  6.     }
  7. }
  8. interface Builder {
  9.     fun buildPartA()
  10.     fun buildPartB()
  11.     fun getResult(): Product
  12. }
  13. class ConcreteBuilder : Builder {
  14.     private val product = Product()
  15.     override fun buildPartA() {
  16.         product.partA = "PartA"
  17.     }
  18.     override fun buildPartB() {
  19.         product.partB = "PartB"
  20.     }
  21.     override fun getResult(): Product {
  22.         return product
  23.     }
  24. }
  25. class Director(private val builder: Builder) {
  26.     fun construct() {
  27.         builder.buildPartA()
  28.         builder.buildPartB()
  29.     }
  30. }
复制代码
1.5 原型模式 (Prototype)

目标: 通过复制现有对象来创建新对象,而不是通过新建类。
Java 实现:
  1. interface Prototype {
  2.     Prototype clone();
  3. }
  4. class ConcretePrototype implements Prototype {
  5.     private String field;
  6.     public ConcretePrototype(String field) {
  7.         this.field = field;
  8.     }
  9.     @Override
  10.     public Prototype clone() {
  11.         return new ConcretePrototype(this.field);
  12.     }
  13.     @Override
  14.     public String toString() {
  15.         return "ConcretePrototype{field='" + field + "'}";
  16.     }
  17. }
复制代码
Kotlin 实现:
  1. interface Prototype {
  2.     fun clone(): Prototype
  3. }
  4. class ConcretePrototype(private val field: String) : Prototype {
  5.     override fun clone(): Prototype {
  6.         return ConcretePrototype(field)
  7.     }
  8.     override fun toString(): String {
  9.         return "ConcretePrototype(field='$field')"
  10.     }
  11. }
复制代码
2. 结构型模式

2.1 适配器模式 (Adapter)

目标: 将一个类的接口转换成客户盼望的另一个接口。
Java 实现:
  1. interface Target {
  2.     void request();
  3. }
  4. class Adaptee {
  5.     public void specificRequest() {
  6.         System.out.println("Specific request");
  7.     }
  8. }
  9. class Adapter implements Target {
  10.     private Adaptee adaptee;
  11.     public Adapter(Adaptee adaptee) {
  12.         this.adaptee = adaptee;
  13.     }
  14.     @Override
  15.     public void request() {
  16.         adaptee.specificRequest();
  17.     }
  18. }
复制代码
Kotlin 实现:
  1. interface Target {
  2.     fun request()
  3. }
  4. class Adaptee {
  5.     fun specificRequest() {
  6.         println("Specific request")
  7.     }
  8. }
  9. class Adapter(private val adaptee: Adaptee) : Target {
  10.     override fun request() {
  11.         adaptee.specificRequest()
  12.     }
  13. }
复制代码
2.2 桥接模式 (Bridge)

目标: 将抽象部分与实现部分分离,使它们可以独立厘革。
Java 实现:
  1. interface Implementor {
  2.     void operationImpl();
  3. }
  4. class ConcreteImplementorA implements Implementor {
  5.     @Override
  6.     public void operationImpl() {
  7.         System.out.println("ConcreteImplementorA operation");
  8.     }
  9. }
  10. class ConcreteImplementorB implements Implementor {
  11.     @Override
  12.     public void operationImpl() {
  13.         System.out.println("ConcreteImplementorB operation");
  14.     }
  15. }
  16. abstract class Abstraction {
  17.     protected Implementor implementor;
  18.     public Abstraction(Implementor implementor) {
  19.         this.implementor = implementor;
  20.     }
  21.     public abstract void operation();
  22. }
  23. class RefinedAbstraction extends Abstraction {
  24.     public RefinedAbstraction(Implementor implementor) {
  25.         super(implementor);
  26.     }
  27.     @Override
  28.     public void operation() {
  29.         implementor.operationImpl();
  30.     }
  31. }
复制代码
Kotlin 实现:
  1. interface Implementor {
  2.     fun operationImpl()
  3. }
  4. class ConcreteImplementorA : Implementor {
  5.     override fun operationImpl() {
  6.         println("ConcreteImplementorA operation")
  7.     }
  8. }
  9. class ConcreteImplementorB : Implementor {
  10.     override fun operationImpl() {
  11.         println("ConcreteImplementorB operation")
  12.     }
  13. }
  14. abstract class Abstraction(protected val implementor: Implementor) {
  15.     abstract fun operation()
  16. }
  17. class RefinedAbstraction(implementor: Implementor) : Abstraction(implementor) {
  18.     override fun operation() {
  19.         implementor.operationImpl()
  20.     }
  21. }
复制代码
2.3 组合模式 (Composite)

目标: 将对象组合成树形结构以体现“部分-整体”的层次结构。
Java 实现:
  1. interface Component {
  2.     void operation();
  3. }
  4. class Leaf implements Component {
  5.     @Override
  6.     public void operation() {
  7.         System.out.println("Leaf operation");
  8.     }
  9. }
  10. class Composite implements Component {
  11.     private List<Component> children = new ArrayList<>();
  12.     public void add(Component component) {
  13.         children.add(component);
  14.     }
  15.     public void remove(Component component) {
  16.         children.remove(component);
  17.     }
  18.     @Override
  19.     public void operation() {
  20.         for (Component component : children) {
  21.             component.operation();
  22.         }
  23.     }
  24. }
复制代码
Kotlin 实现:
  1. interface Component {
  2.     fun operation()
  3. }
  4. class Leaf : Component {
  5.     override fun operation() {
  6.         println("Leaf operation")
  7.     }
  8. }
  9. class Composite : Component {
  10.     private val children = mutableListOf<Component>()
  11.     fun add(component: Component) {
  12.         children.add(component)
  13.     }
  14.     fun remove(component: Component) {
  15.         children.remove(component)
  16.     }
  17.     override fun operation() {
  18.         for (component in children) {
  19.             component.operation()
  20.         }
  21.     }
  22. }
复制代码
2.4 装饰器模式 (Decorator)

目标: 动态地给对象添加一些额外的职责。
Java 实现:
  1. interface Component {
  2.     void operation();
  3. }
  4. class ConcreteComponent implements Component {
  5.     @Override
  6.     public void operation() {
  7.         System.out.println("ConcreteComponent operation");
  8.     }
  9. }
  10. abstract class Decorator implements Component {
  11.     protected Component component;
  12.     public Decorator(Component component) {
  13.         this.component = component;
  14.     }
  15.     @Override
  16.     public void operation() {
  17.         component.operation();
  18.     }
  19. }
  20. class ConcreteDecoratorA extends Decorator {
  21.     public ConcreteDecoratorA(Component component) {
  22.         super(component);
  23.     }
  24.     @Override
  25.     public void operation() {
  26.         super.operation();
  27.         addedBehavior();
  28.     }
  29.     private void addedBehavior() {
  30.         System.out.println("ConcreteDecoratorA added behavior");
  31.     }
  32. }
  33. class ConcreteDecoratorB extends Decorator {
  34.     public ConcreteDecoratorB(Component component) {
  35.         super(component);
  36.     }
  37.     @Override
  38.     public void operation() {
  39.         super.operation();
  40.         addedBehavior();
  41.     }
  42.     private void addedBehavior() {
  43.         System.out.println("ConcreteDecoratorB added behavior");
  44.     }
  45. }
复制代码
Kotlin 实现:
  1. interface Component {
  2.     fun operation()
  3. }
  4. class ConcreteComponent : Component {
  5.     override fun operation() {
  6.         println("ConcreteComponent operation")
  7.     }
  8. }
  9. abstract class Decorator(private val component: Component) : Component {
  10.     override fun operation() {
  11.         component.operation()
  12.     }
  13. }
  14. class ConcreteDecoratorA(component: Component) : Decorator(component) {
  15.     override fun operation() {
  16.         super.operation()
  17.         addedBehavior()
  18.     }
  19.     private fun addedBehavior() {
  20.         println("ConcreteDecoratorA added behavior")
  21.     }
  22. }
  23. class ConcreteDecoratorB(component: Component) : Decorator(component) {
  24.     override fun operation() {
  25.         super.operation()
  26.         addedBehavior()
  27.     }
  28.     private fun addedBehavior() {
  29.         println("ConcreteDecoratorB added behavior")
  30.     }
  31. }
复制代码
2.5 外观模式 (Facade)

目标: 为子系统中的一组接口提供一个同一的接口。
Java 实现:
  1. class SubsystemA {
  2.     public void operationA() {
  3.         System.out.println("SubsystemA operation");
  4.     }
  5. }
  6. class SubsystemB {
  7.     public void operationB() {
  8.         System.out.println("SubsystemB operation");
  9.     }
  10. }
  11. class Facade {
  12.     private SubsystemA subsystemA = new SubsystemA();
  13.     private SubsystemB subsystemB = new SubsystemB();
  14.     public void operation() {
  15.         subsystemA.operationA();
  16.         subsystemB.operationB();
  17.     }
  18. }
复制代码
Kotlin 实现:
  1. class SubsystemA {
  2.     fun operationA() {
  3.         println("SubsystemA operation")
  4.     }
  5. }
  6. class SubsystemB {
  7.     fun operationB() {
  8.         println("SubsystemB operation")
  9.     }
  10. }
  11. class Facade {
  12.     private val subsystemA = SubsystemA()
  13.     private val subsystemB = SubsystemB()
  14.     fun operation() {
  15.         subsystemA.operationA()
  16.         subsystemB.operationB()
  17.     }
  18. }
复制代码
2.6 享元模式 (Flyweight)

目标: 运用共享技能有效地支持大量细粒度的对象。
Java 实现:
  1. class Flyweight {
  2.     private String intrinsicState;
  3.     public Flyweight(String intrinsicState) {
  4.         this.intrinsicState = intrinsicState;
  5.     }
  6.     public void operation(String extrinsicState) {
  7.         System.out.println("Intrinsic State = " + intrinsicState + ", Extrinsic State = " + extrinsicState);
  8.     }
  9. }
  10. class FlyweightFactory {
  11.     private Map<String, Flyweight> flyweights = new HashMap<>();
  12.     public Flyweight getFlyweight(String key) {
  13.         if (!flyweights.containsKey(key)) {
  14.             flyweights.put(key, new Flyweight(key));
  15.         }
  16.         return flyweights.get(key);
  17.     }
  18. }
复制代码
Kotlin 实现:
  1. class Flyweight(private val intrinsicState: String) {
  2.     fun operation(extrinsicState: String) {
  3.         println("Intrinsic State = $intrinsicState, Extrinsic State = $extrinsicState")
  4.     }
  5. }
  6. class FlyweightFactory {
  7.     private val flyweights = mutableMapOf<String, Flyweight>()
  8.     fun getFlyweight(key: String): Flyweight {
  9.         return flyweights.getOrPut(key) { Flyweight(key) }
  10.     }
  11. }
复制代码
2.7 署理模式 (Proxy)

目标: 为其他对象提供一个署理以控制对这个对象的访问。
Java 实现:
  1. interface Subject {
  2.     void request();
  3. }
  4. class RealSubject implements Subject {
  5.     @Override
  6.     public void request() {
  7.         System.out.println("RealSubject request");
  8.     }
  9. }
  10. class Proxy implements Subject {
  11.     private RealSubject realSubject;
  12.     @Override
  13.     public void request() {
  14.         if (realSubject == null) {
  15.             realSubject = new RealSubject();
  16.         }
  17.         realSubject.request();
  18.     }
  19. }
复制代码
Kotlin 实现:
  1. interface Subject {
  2.     fun request()
  3. }
  4. class RealSubject : Subject {
  5.     override fun request() {
  6.         println("RealSubject request")
  7.     }
  8. }
  9. class Proxy : Subject {
  10.     private var realSubject: RealSubject? = null
  11.     override fun request() {
  12.         if (realSubject == null) {
  13.             realSubject = RealSubject()
  14.         }
  15.         realSubject?.request()
  16.     }
  17. }
复制代码
3. 举动型模式

3.1 责任链模式 (Chain of Responsibility)

目标: 使多个对象都有时机处置处罚请求,从而避免请求的发送者与吸收者之间的耦合。
Java 实现:
  1. abstract class Handler {
  2.     protected Handler successor;
  3.     public void setSuccessor(Handler successor) {
  4.         this.successor = successor;
  5.     }
  6.     public abstract void handleRequest(String request);
  7. }
  8. class ConcreteHandlerA extends Handler {
  9.     @Override
  10.     public void handleRequest(String request) {
  11.         if (request.equals("A")) {
  12.             System.out.println("ConcreteHandlerA handles request");
  13.         } else if (successor != null) {
  14.             successor.handleRequest(request);
  15.         }
  16.     }
  17. }
  18. class ConcreteHandlerB extends Handler {
  19.     @Override
  20.     public void handleRequest(String request) {
  21.         if (request.equals("B")) {
  22.             System.out.println("ConcreteHandlerB handles request");
  23.         } else if (successor != null) {
  24.             successor.handleRequest(request);
  25.         }
  26.     }
  27. }
复制代码
Kotlin 实现:
  1. abstract class Handler {
  2.     var successor: Handler? = null
  3.     abstract fun handleRequest(request: String)
  4. }
  5. class ConcreteHandlerA : Handler() {
  6.     override fun handleRequest(request: String) {
  7.         if (request == "A") {
  8.             println("ConcreteHandlerA handles request")
  9.         } else {
  10.             successor?.handleRequest(request)
  11.         }
  12.     }
  13. }
  14. class ConcreteHandlerB : Handler() {
  15.     override fun handleRequest(request: String) {
  16.         if (request == "B") {
  17.             println("ConcreteHandlerB handles request")
  18.         } else {
  19.             successor?.handleRequest(request)
  20.         }
  21.     }
  22. }
复制代码
3.2 下令模式 (Command)

目标: 将请求封装为对象,从而使你可以用不同的请求对客户进行参数化。
Java 实现:
  1. interface Command {
  2.     void execute();
  3. }
  4. class ConcreteCommand implements Command {
  5.     private Receiver receiver;
  6.     public ConcreteCommand(Receiver receiver) {
  7.         this.receiver = receiver;
  8.     }
  9.     @Override
  10.     public void execute() {
  11.         receiver.action();
  12.     }
  13. }
  14. class Receiver {
  15.     public void action() {
  16.         System.out.println("Receiver action");
  17.     }
  18. }
  19. class Invoker {
  20.     private Command command;
  21.     public void setCommand(Command command) {
  22.         this.command = command;
  23.     }
  24.     public void executeCommand() {
  25.         command.execute();
  26.     }
  27. }
复制代码
Kotlin 实现:
  1. interface Command {
  2.     fun execute()
  3. }
  4. class ConcreteCommand(private val receiver: Receiver) : Command {
  5.     override fun execute() {
  6.         receiver.action()
  7.     }
  8. }
  9. class Receiver {
  10.     fun action() {
  11.         println("Receiver action")
  12.     }
  13. }
  14. class Invoker {
  15.     private var command: Command? = null
  16.     fun setCommand(command: Command) {
  17.         this.command = command
  18.     }
  19.     fun executeCommand() {
  20.         command?.execute()
  21.     }
  22. }
复制代码
3.3 解释器模式 (Interpreter)

目标: 给定一个语言,定义它的文法的一种体现,并定义一个解释器,这个解释器使用该体现来解释语言中的句子。
Java 实现:
  1. class OrExpression implements Expression {
  2.     private Expression expr1;
  3.     private Expression expr2;
  4.     public OrExpression(Expression expr1, Expression expr2) {
  5.         this.expr1 = expr1;
  6.         this.expr2 = expr2;
  7.     }
  8.     @Override
  9.     public boolean interpret(String context) {
  10.         return expr1.interpret(context) || expr2.interpret(context);
  11.     }
  12. }
  13. class AndExpression implements Expression {
  14.     private Expression expr1;
  15.     private Expression expr2;
  16.     public AndExpression(Expression expr1, Expression expr2) {
  17.         this.expr1 = expr1;
  18.         this.expr2 = expr2;
  19.     }
  20.     @Override
  21.     public boolean interpret(String context) {
  22.         return expr1.interpret(context) && expr2.interpret(context);
  23.     }
  24. }
  25. // 使用示例
  26. public class InterpreterPatternDemo {
  27.     public static void main(String[] args) {
  28.         Expression isMale = new TerminalExpression("John");
  29.         Expression isMarriedWoman = new AndExpression(new TerminalExpression("Julie"), new TerminalExpression("Married"));
  30.         Expression isSingleOrMale = new OrExpression(isMale, new TerminalExpression("Single"));
  31.         System.out.println("John is male? " + isMale.interpret("John"));
  32.         System.out.println("Julie is a married woman? " + isMarriedWoman.interpret("Married Julie"));
  33.         System.out.println("Is John single or male? " + isSingleOrMale.interpret("Single John"));
  34.     }
  35. }
复制代码
Kotlin 实现:
  1. interface Expression {
  2.     fun interpret(context: String): Boolean
  3. }
  4. class TerminalExpression(private val data: String) : Expression {
  5.     override fun interpret(context: String): Boolean {
  6.         return context.contains(data)
  7.     }
  8. }
  9. class OrExpression(private val expr1: Expression, private val expr2: Expression) : Expression {
  10.     override fun interpret(context: String): Boolean {
  11.         return expr1.interpret(context) || expr2.interpret(context)
  12.     }
  13. }
  14. class AndExpression(private val expr1: Expression, private val expr2: Expression) : Expression {
  15.     override fun interpret(context: String): Boolean {
  16.         return expr1.interpret(context) && expr2.interpret(context)
  17.     }
  18. }
  19. // 使用示例
  20. fun main() {
  21.     val isMale = TerminalExpression("John")
  22.     val isMarriedWoman = AndExpression(TerminalExpression("Julie"), TerminalExpression("Married"))
  23.     val isSingleOrMale = OrExpression(isMale, TerminalExpression("Single"))
  24.     println("John is male? ${isMale.interpret("John")}")
  25.     println("Julie is a married woman? ${isMarriedWoman.interpret("Married Julie")}")
  26.     println("Is John single or male? ${isSingleOrMale.interpret("Single John")}")
  27. }
复制代码
3.4 迭代器模式 (Iterator)

目标: 提供一种方法序次访问一个聚合对象中的各个元素,而又不暴露其内部体现。
Java 实现:
  1. interface Iterator<T> {
  2.     boolean hasNext();
  3.     T next();
  4. }
  5. interface Container<T> {
  6.     Iterator<T> getIterator();
  7. }
  8. class NameRepository implements Container<String> {
  9.     private String[] names = {"John", "Julie", "Adam", "Eve"};
  10.     @Override
  11.     public Iterator<String> getIterator() {
  12.         return new NameIterator();
  13.     }
  14.     private class NameIterator implements Iterator<String> {
  15.         private int index;
  16.         @Override
  17.         public boolean hasNext() {
  18.             return index < names.length;
  19.         }
  20.         @Override
  21.         public String next() {
  22.             if (hasNext()) {
  23.                 return names[index++];
  24.             }
  25.             return null;
  26.         }
  27.     }
  28. }
  29. // 使用示例
  30. public class IteratorPatternDemo {
  31.     public static void main(String[] args) {
  32.         NameRepository nameRepository = new NameRepository();
  33.         Iterator<String> iterator = nameRepository.getIterator();
  34.         while (iterator.hasNext()) {
  35.             System.out.println("Name: " + iterator.next());
  36.         }
  37.     }
  38. }
复制代码
Kotlin 实现:
  1. interface Iterator<T> {
  2.     fun hasNext(): Boolean
  3.     fun next(): T
  4. }
  5. interface Container<T> {
  6.     fun getIterator(): Iterator<T>
  7. }
  8. class NameRepository : Container<String> {
  9.     private val names = arrayOf("John", "Julie", "Adam", "Eve")
  10.     override fun getIterator(): Iterator<String> {
  11.         return NameIterator()
  12.     }
  13.     private inner class NameIterator : Iterator<String> {
  14.         private var index = 0
  15.         override fun hasNext(): Boolean {
  16.             return index < names.size
  17.         }
  18.         override fun next(): String {
  19.             return if (hasNext()) {
  20.                 names[index++]
  21.             } else {
  22.                 throw NoSuchElementException()
  23.             }
  24.         }
  25.     }
  26. }
  27. // 使用示例
  28. fun main() {
  29.     val nameRepository = NameRepository()
  30.     val iterator = nameRepository.getIterator()
  31.     while (iterator.hasNext()) {
  32.         println("Name: ${iterator.next()}")
  33.     }
  34. }
复制代码
3.5 中介者模式 (Mediator)

目标: 定义一个中介对象来封装一系列对象之间的交互,使它们不需要显式地相互引用。
Java 实现:
  1. interface Mediator {
  2.     void send(String message, Colleague colleague);
  3. }
  4. abstract class Colleague {
  5.     protected Mediator mediator;
  6.     public Colleague(Mediator mediator) {
  7.         this.mediator = mediator;
  8.     }
  9.     public abstract void send(String message);
  10.     public abstract void receive(String message);
  11. }
  12. class ConcreteColleagueA extends Colleague {
  13.     public ConcreteColleagueA(Mediator mediator) {
  14.         super(mediator);
  15.     }
  16.     @Override
  17.     public void send(String message) {
  18.         mediator.send(message, this);
  19.     }
  20.     @Override
  21.     public void receive(String message) {
  22.         System.out.println("ConcreteColleagueA received: " + message);
  23.     }
  24. }
  25. class ConcreteColleagueB extends Colleague {
  26.     public ConcreteColleagueB(Mediator mediator) {
  27.         super(mediator);
  28.     }
  29.     @Override
  30.     public void send(String message) {
  31.         mediator.send(message, this);
  32.     }
  33.     @Override
  34.     public void receive(String message) {
  35.         System.out.println("ConcreteColleagueB received: " + message);
  36.     }
  37. }
  38. class ConcreteMediator implements Mediator {
  39.     private ConcreteColleagueA colleagueA;
  40.     private ConcreteColleagueB colleagueB;
  41.     public void setColleagueA(ConcreteColleagueA colleagueA) {
  42.         this.colleagueA = colleagueA;
  43.     }
  44.     public void setColleagueB(ConcreteColleagueB colleagueB) {
  45.         this.colleagueB = colleagueB;
  46.     }
  47.     @Override
  48.     public void send(String message, Colleague colleague) {
  49.         if (colleague == colleagueA) {
  50.             colleagueB.receive(message);
  51.         } else {
  52.             colleagueA.receive(message);
  53.         }
  54.     }
  55. }
  56. // 使用示例
  57. public class MediatorPatternDemo {
  58.     public static void main(String[] args) {
  59.         ConcreteMediator mediator = new ConcreteMediator();
  60.         ConcreteColleagueA colleagueA = new ConcreteColleagueA(mediator);
  61.         ConcreteColleagueB colleagueB = new ConcreteColleagueB(mediator);
  62.         mediator.setColleagueA(colleagueA);
  63.         mediator.setColleagueB(colleagueB);
  64.         colleagueA.send("Hello from A");
  65.         colleagueB.send("Hi from B");
  66.     }
  67. }
复制代码
Kotlin 实现:
  1. interface Mediator {
  2.     fun send(message: String, colleague: Colleague)
  3. }
  4. abstract class Colleague(protected val mediator: Mediator) {
  5.     abstract fun send(message: String)
  6.     abstract fun receive(message: String)
  7. }
  8. class ConcreteColleagueA(mediator: Mediator) : Colleague(mediator) {
  9.     override fun send(message: String) {
  10.         mediator.send(message, this)
  11.     }
  12.     override fun receive(message: String) {
  13.         println("ConcreteColleagueA received: $message")
  14.     }
  15. }
  16. class ConcreteColleagueB(mediator: Mediator) : Colleague(mediator) {
  17.     override fun send(message: String) {
  18.         mediator.send(message, this)
  19.     }
  20.     override fun receive(message: String) {
  21.         println("ConcreteColleagueB received: $message")
  22.     }
  23. }
  24. class ConcreteMediator : Mediator {
  25.     private lateinit var colleagueA: ConcreteColleagueA
  26.     private lateinit var colleagueB: ConcreteColleagueB
  27.     fun setColleagueA(colleagueA: ConcreteColleagueA) {
  28.         this.colleagueA = colleagueA
  29.     }
  30.     fun setColleagueB(colleagueB: ConcreteColleagueB) {
  31.         this.colleagueB = colleagueB
  32.     }
  33.     override fun send(message: String, colleague: Colleague) {
  34.         when (colleague) {
  35.             colleagueA -> colleagueB.receive(message)
  36.             else -> colleagueA.receive(message)
  37.         }
  38.     }
  39. }
  40. // 使用示例
  41. fun main() {
  42.     val mediator = ConcreteMediator()
  43.     val colleagueA = ConcreteColleagueA(mediator)
  44.     val colleagueB = ConcreteColleagueB(mediator)
  45.     mediator.setColleagueA(colleagueA)
  46.     mediator.setColleagueB(colleagueB)
  47.     colleagueA.send("Hello from A")
  48.     colleagueB.send("Hi from B")
  49. }
复制代码
3.6 备忘录模式 (Memento)

目标: 在不粉碎封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
Java 实现:
  1. class Memento {
  2.     private String state;
  3.     public Memento(String state) {
  4.         this.state = state;
  5.     }
  6.     public String getState() {
  7.         return state;
  8.     }
  9. }
  10. class Originator {
  11.     private String state;
  12.     public void setState(String state) {
  13.         this.state = state;
  14.     }
  15.     public String getState() {
  16.         return state;
  17.     }
  18.     public Memento saveStateToMemento() {
  19.         return new Memento(state);
  20.     }
  21.     public void getStateFromMemento(Memento memento) {
  22.         state = memento.getState();
  23.     }
  24. }
  25. class CareTaker {
  26.     private List<Memento> mementoList = new ArrayList<>();
  27.     public void add(Memento state) {
  28.         mementoList.add(state);
  29.     }
  30.     public Memento get(int index) {
  31.         return mementoList.get(index);
  32.     }
  33. }
  34. // 使用示例
  35. public class MementoPatternDemo {
  36.     public static void main(String[] args) {
  37.         Originator originator = new Originator();
  38.         CareTaker careTaker = new CareTaker();
  39.         originator.setState("State #1");
  40.         careTaker.add(originator.saveStateToMemento());
  41.         originator.setState("State #2");
  42.         careTaker.add(originator.saveStateToMemento());
  43.         originator.setState("State #3");
  44.         careTaker.add(originator.saveStateToMemento());
  45.         System.out.println("Current State: " + originator.getState());
  46.         originator.getStateFromMemento(careTaker.get(0));
  47.         System.out.println("First saved State: " + originator.getState());
  48.         originator.getStateFromMemento(careTaker.get(1));
  49.         System.out.println("Second saved State: " + originator.getState());
  50.     }
  51. }
复制代码
Kotlin 实现:
  1. class Memento(val state: String)
  2. class Originator {
  3.     private var state: String = ""
  4.     fun setState(state: String) {
  5.         this.state = state
  6.     }
  7.     fun getState(): String {
  8.         return state
  9.     }
  10.     fun saveStateToMemento(): Memento {
  11.         return Memento(state)
  12.     }
  13.     fun getStateFromMemento(memento: Memento) {
  14.         state = memento.state
  15.     }
  16. }
  17. class CareTaker {
  18.     private val mementoList = mutableListOf<Memento>()
  19.     fun add(state: Memento) {
  20.         mementoList.add(state)
  21.     }
  22.     fun get(index: Int): Memento {
  23.         return mementoList[index]
  24.     }
  25. }
  26. // 使用示例
  27. fun main() {
  28.     val originator = Originator()
  29.     val careTaker = CareTaker()
  30.     originator.setState("State #1")
  31.     careTaker.add(originator.saveStateToMemento())
  32.     originator.setState("State #2")
  33.     careTaker.add(originator.saveStateToMemento())
  34.     originator.setState("State #3")
  35.     careTaker.add(originator.saveStateToMemento())
  36.     println("Current State: ${originator.getState()}")
  37.     originator.getStateFromMemento(careTaker.get(0))
  38.     println("First saved State: ${originator.getState()}")
  39.     originator.getStateFromMemento(careTaker.get(1))
  40.     println("Second saved State: ${originator.getState()}")
  41. }
复制代码
3.7 观察者模式 (Observer)

目标: 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,全部依赖于它的对象都得到通知并被自动更新。
Java 实现:
  1. interface Observer {
  2.     void update(String message);
  3. }
  4. class ConcreteObserver implements Observer {
  5.     private String name;
  6.     public ConcreteObserver(String name) {
  7.         this.name = name;
  8.     }
  9.     @Override
  10.     public void update(String message) {
  11.         System.out.println(name + " received message: " + message);
  12.     }
  13. }
  14. class Subject {
  15.     private List<Observer> observers = new ArrayList<>();
  16.     private String state;
  17.     public void setState(String state) {
  18.         this.state = state;
  19.         notifyAllObservers();
  20.     }
  21.     public void attach(Observer observer) {
  22.         observers.add(observer);
  23.     }
  24.     public void notifyAllObservers() {
  25.         for (Observer observer : observers) {
  26.             observer.update(state);
  27.         }
  28.     }
  29. }
  30. // 使用示例
  31. public class ObserverPatternDemo {
  32.     public static void main(String[] args) {
  33.         Subject subject = new Subject();
  34.         Observer observer1 = new ConcreteObserver("Observer 1");
  35.         Observer observer2 = new ConcreteObserver("Observer 2");
  36.         subject.attach(observer1);
  37.         subject.attach(observer2);
  38.         subject.setState("State #1");
  39.         subject.setState("State #2");
  40.     }
  41. }
复制代码
Kotlin 实现:
  1. interface Observer {
  2.     fun update(message: String)
  3. }
  4. class ConcreteObserver(private val name: String) : Observer {
  5.     override fun update(message: String) {
  6.         println("$name received message: $message")
  7.     }
  8. }
  9. class Subject {
  10.     private val observers = mutableListOf<Observer>()
  11.     private var state: String = ""
  12.     fun setState(state: String) {
  13.         this.state = state
  14.         notifyAllObservers()
  15.     }
  16.     fun attach(observer: Observer) {
  17.         observers.add(observer)
  18.     }
  19.     private fun notifyAllObservers() {
  20.         for (observer in observers) {
  21.             observer.update(state)
  22.         }
  23.     }
  24. }
  25. // 使用示例
  26. fun main() {
  27.     val subject = Subject()
  28.     val observer1 = ConcreteObserver("Observer 1")
  29.     val observer2 = ConcreteObserver("Observer 2")
  30.     subject.attach(observer1)
  31.     subject.attach(observer2)
  32.     subject.setState("State #1")
  33.     subject.setState("State #2")
  34. }
复制代码
3.8 状态模式 (State)

目标: 允许一个对象在其内部状态改变时改变它的举动。
Java 实现:
  1. interface State {
  2.     void handle(Context context);
  3. }
  4. class ConcreteStateA implements State {
  5.     @Override
  6.     public void handle(Context context) {
  7.         System.out.println("Handling in State A");
  8.         context.setState(new ConcreteStateB());
  9.     }
  10. }
  11. class ConcreteStateB implements State {
  12.     @Override
  13.     public void handle(Context context) {
  14.         System.out.println("Handling in State B");
  15.         context.setState(new ConcreteStateA());
  16.     }
  17. }
  18. class Context {
  19.     private State state;
  20.     public Context(State state) {
  21.         this.state = state;
  22.     }
  23.     public void setState(State state) {
  24.         this.state = state;
  25.     }
  26.     public void request() {
  27.         state.handle(this);
  28.     }
  29. }
  30. // 使用示例
  31. public class StatePatternDemo {
  32.     public static void main(String[] args) {
  33.         Context context = new Context(new ConcreteStateA());
  34.         context.request();
  35.         context.request();
  36.         context.request();
  37.     }
  38. }
复制代码
Kotlin 实现:
  1. interface State {
  2.     fun handle(context: Context)
  3. }
  4. class ConcreteStateA : State {
  5.     override fun handle(context: Context) {
  6.         println("Handling in State A")
  7.         context.setState(ConcreteStateB())
  8.     }
  9. }
  10. class ConcreteStateB : State {
  11.     override fun handle(context: Context) {
  12.         println("Handling in State B")
  13.         context.setState(ConcreteStateA())
  14.     }
  15. }
  16. class Context(private var state: State) {
  17.     fun setState(state: State) {
  18.         this.state = state
  19.     }
  20.     fun request() {
  21.         state.handle(this)
  22.     }
  23. }
  24. // 使用示例
  25. fun main() {
  26.     val context = Context(ConcreteStateA())
  27.     context.request()
  28.     context.request()
  29.     context.request()
  30. }
复制代码
3.9 计谋模式 (Strategy)

目标: 定义一系列算法,将它们封装起来,并且使它们可以相互更换。
Java 实现:
  1. interface Strategy {
  2.     int doOperation(int num1, int num2);
  3. }
  4. class OperationAdd implements Strategy {
  5.     @Override
  6.     public int doOperation(int num1, int num2) {
  7.         return num1 + num2;
  8.     }
  9. }
  10. class OperationSubtract implements Strategy {
  11.     @Override
  12.     public int doOperation(int num1, int num2) {
  13.         return num1 - num2;
  14.     }
  15. }
  16. class OperationMultiply implements Strategy {
  17.     @Override
  18.     public int doOperation(int num1, int num2) {
  19.         return num1 * num2;
  20.     }
  21. }
  22. class Context {
  23.     private Strategy strategy;
  24.     public Context(Strategy strategy) {
  25.         this.strategy = strategy;
  26.     }
  27.     public int executeStrategy(int num1, int num2) {
  28.         return strategy.doOperation(num1, num2);
  29.     }
  30. }
  31. // 使用示例
  32. public class StrategyPatternDemo {
  33.     public static void main(String[] args) {
  34.         Context context = new Context(new OperationAdd());
  35.         System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
  36.         context = new Context(new OperationSubtract());
  37.         System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
  38.         context = new Context(new OperationMultiply());
  39.         System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
  40.     }
  41. }
复制代码
Kotlin 实现:
  1. interface Strategy {
  2.     fun doOperation(num1: Int, num2: Int): Int
  3. }
  4. class OperationAdd : Strategy {
  5.     override fun doOperation(num1: Int, num2: Int): Int {
  6.         return num1 + num2
  7.     }
  8. }
  9. class OperationSubtract : Strategy {
  10.     override fun doOperation(num1: Int, num2: Int): Int {
  11.         return num1 - num2
  12.     }
  13. }
  14. class OperationMultiply : Strategy {
  15.     override fun doOperation(num1: Int, num2: Int): Int {
  16.         return num1 * num2
  17.     }
  18. }
  19. class Context(private var strategy: Strategy) {
  20.     fun executeStrategy(num1: Int, num2: Int): Int {
  21.         return strategy.doOperation(num1, num2)
  22.     }
  23. }
  24. // 使用示例
  25. fun main() {
  26.     var context = Context(OperationAdd())
  27.     println("10 + 5 = ${context.executeStrategy(10, 5)}")
  28.     context = Context(OperationSubtract())
  29.     println("10 - 5 = ${context.executeStrategy(10, 5)}")
  30.     context = Context(OperationMultiply())
  31.     println("10 * 5 = ${context.executeStrategy(10, 5)}")
  32. }
复制代码
3.10 模板方法模式 (Template Method)

目标: 定义一个操作中的算法骨架,而将一些步骤延迟到子类中。
Java 实现:
  1. abstract class Game {
  2.     abstract void initialize();
  3.     abstract void startPlay();
  4.     abstract void endPlay();
  5.     // 模板方法
  6.     public final void play() {
  7.         initialize();
  8.         startPlay();
  9.         endPlay();
  10.     }
  11. }
  12. class Cricket extends Game {
  13.     @Override
  14.     void initialize() {
  15.         System.out.println("Cricket Game Initialized!");
  16.     }
  17.     @Override
  18.     void startPlay() {
  19.         System.out.println("Cricket Game Started!");
  20.     }
  21.     @Override
  22.     void endPlay() {
  23.         System.out.println("Cricket Game Finished!");
  24.     }
  25. }
  26. class Football extends Game {
  27.     @Override
  28.     void initialize() {
  29.         System.out.println("Football Game Initialized!");
  30.     }
  31.     @Override
  32.     void startPlay() {
  33.         System.out.println("Football Game Started!");
  34.     }
  35.     @Override
  36.     void endPlay() {
  37.         System.out.println("Football Game Finished!");
  38.     }
  39. }
  40. // 使用示例
  41. public class TemplateMethodPatternDemo {
  42.     public static void main(String[] args) {
  43.         Game game = new Cricket();
  44.         game.play();
  45.         game = new Football();
  46.         game.play();
  47.     }
  48. }
复制代码
Kotlin 实现:
  1. abstract class Game {
  2.     abstract fun initialize()
  3.     abstract fun startPlay()
  4.     abstract fun endPlay()
  5.     // 模板方法
  6.     fun play() {
  7.         initialize()
  8.         startPlay()
  9.         endPlay()
  10.     }
  11. }
  12. class Cricket : Game() {
  13.     override fun initialize() {
  14.         println("Cricket Game Initialized!")
  15.     }
  16.     override fun startPlay() {
  17.         println("Cricket Game Started!")
  18.     }
  19.     override fun endPlay() {
  20.         println("Cricket Game Finished!")
  21.     }
  22. }
  23. class Football : Game() {
  24.     override fun initialize() {
  25.         println("Football Game Initialized!")
  26.     }
  27.     override fun startPlay() {
  28.         println("Football Game Started!")
  29.     }
  30.     override fun endPlay() {
  31.         println("Football Game Finished!")
  32.     }
  33. }
  34. // 使用示例
  35. fun main() {
  36.     var game: Game = Cricket()
  37.     game.play()
  38.     game = Football()
  39.     game.play()
  40. }
复制代码
3.11 访问者模式 (Visitor)

目标: 体现一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
Java 实现:
  1. interface ComputerPartVisitor {
  2.     void visit(Computer computer);
  3.     void visit(Mouse mouse);
  4.     void visit(Keyboard keyboard);
  5.     void visit(Monitor monitor);
  6. }
  7. interface ComputerPart {
  8.     void accept(ComputerPartVisitor computerPartVisitor);
  9. }
  10. class Keyboard implements ComputerPart {
  11.     @Override
  12.     public void accept(ComputerPartVisitor computerPartVisitor) {
  13.         computerPartVisitor.visit(this);
  14.     }
  15. }
  16. class Monitor implements ComputerPart {
  17.     @Override
  18.     public void accept(ComputerPartVisitor computerPartVisitor) {
  19.         computerPartVisitor.visit(this);
  20.     }
  21. }
  22. class Mouse implements ComputerPart {
  23.     @Override
  24.     public void accept(ComputerPartVisitor computerPartVisitor) {
  25.         computerPartVisitor.visit(this);
  26.     }
  27. }
  28. class Computer implements ComputerPart {
  29.     ComputerPart[] parts;
  30.     public Computer() {
  31.         parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
  32.     }
  33.     @Override
  34.     public void accept(ComputerPartVisitor computerPartVisitor) {
  35.         for (ComputerPart part : parts) {
  36.             part.accept(computerPartVisitor);
  37.         }
  38.         computerPartVisitor.visit(this);
  39.     }
  40. }
  41. class ComputerPartDisplayVisitor implements ComputerPartVisitor {
  42.     @Override
  43.     public void visit(Computer computer) {
  44.         System.out.println("Displaying Computer.");
  45.     }
  46.     @Override
  47.     public void visit(Mouse mouse) {
  48.         System.out.println("Displaying Mouse.");
  49.     }
  50.     @Override
  51.     public void visit(Keyboard keyboard) {
  52.         System.out.println("Displaying Keyboard.");
  53.     }
  54.     @Override
  55.     public void visit(Monitor monitor) {
  56.         System.out.println("Displaying Monitor.");
  57.     }
  58. }
  59. // 使用示例
  60. public class VisitorPatternDemo {
  61.     public static void main(String[] args) {
  62.         ComputerPart computer = new Computer();
  63.         computer.accept(new ComputerPartDisplayVisitor());
  64.     }
  65. }
复制代码
Kotlin 实现:
  1. interface ComputerPartVisitor {
  2.     fun visit(computer: Computer)
  3.     fun visit(mouse: Mouse)
  4.     fun visit(keyboard: Keyboard)
  5.     fun visit(monitor: Monitor)
  6. }
  7. interface ComputerPart {
  8.     fun accept(computerPartVisitor: ComputerPartVisitor)
  9. }
  10. class Keyboard : ComputerPart {
  11.     override fun accept(computerPartVisitor: ComputerPartVisitor) {
  12.         computerPartVisitor.visit(this)
  13.     }
  14. }
  15. class Monitor : ComputerPart {
  16.     override fun accept(computerPartVisitor: ComputerPartVisitor) {
  17.         computerPartVisitor.visit(this)
  18.     }
  19. }
  20. class Mouse : ComputerPart {
  21.     override fun accept(computerPartVisitor: ComputerPartVisitor) {
  22.         computerPartVisitor.visit(this)
  23.     }
  24. }
  25. class Computer : ComputerPart {
  26.     private val parts = arrayOf(Mouse(), Keyboard(), Monitor())
  27.     override fun accept(computerPartVisitor: ComputerPartVisitor) {
  28.         for (part in parts) {
  29.             part.accept(computerPartVisitor)
  30.         }
  31.         computerPartVisitor.visit(this)
  32.     }
  33. }
  34. class ComputerPartDisplayVisitor : ComputerPartVisitor {
  35.     override fun visit(computer: Computer) {
  36.         println("Displaying Computer.")
  37.     }
  38.     override fun visit(mouse: Mouse) {
  39.         println("Displaying Mouse.")
  40.     }
  41.     override fun visit(keyboard: Keyboard) {
  42.         println("Displaying Keyboard.")
  43.     }
  44.     override fun visit(monitor: Monitor) {
  45.         println("Displaying Monitor.")
  46.     }
  47. }
  48. // 使用示例
  49. fun main() {
  50.     val computer = Computer()
  51.     computer.accept(ComputerPartDisplayVisitor())
  52. }
复制代码

以上是 23 种设计模式的详细实现,涵盖了创建型、结构型和举动型模式。每种模式都提供了 Java 和 Kotlin 的实现示例,并附有简朴的使用示例。盼望这些内容能帮助你更好地理解设计模式,并在实际开发中机动运用!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

悠扬随风

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表