设计模式是软件开发中办理常见问题的经典办理方案模板。它们帮助开发者编写可维护、可扩展和可重用的代码。本文详细介绍了 23 种经典设计模式,包括创建型、结构型和举动型模式,并提供了 Java 和 Kotlin 的完整实现示例。无论你是初学者照旧有履历的开发者,本文都能帮助你深入理解设计模式的核心思想,并将其应用到实际项目中。
Java 和 Kotlin 实现 23 种设计模式
设计模式是软件开发中常见问题的办理方案模板。它们帮助开发者编写可维护、可扩展和可重用的代码。本文将详细介绍 23 种经典设计模式,并提供 Java 和 Kotlin 的实现示例。
1. 创建型模式
1.1 单例模式 (Singleton)
目标: 确保一个类只有一个实例,并提供全局访问点。
Java 实现:
- public class Singleton {
- private static Singleton instance;
- private Singleton() {}
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
复制代码 Kotlin 实现:
1.2 工厂方法模式 (Factory Method)
目标: 定义一个创建对象的接口,但让子类决定实例化哪个类。
Java 实现:
- interface Product {
- void use();
- }
- class ConcreteProduct implements Product {
- @Override
- public void use() {
- System.out.println("Using ConcreteProduct");
- }
- }
- abstract class Creator {
- public abstract Product factoryMethod();
- }
- class ConcreteCreator extends Creator {
- @Override
- public Product factoryMethod() {
- return new ConcreteProduct();
- }
- }
复制代码 Kotlin 实现:
- interface Product {
- fun use()
- }
- class ConcreteProduct : Product {
- override fun use() {
- println("Using ConcreteProduct")
- }
- }
- abstract class Creator {
- abstract fun factoryMethod(): Product
- }
- class ConcreteCreator : Creator() {
- override fun factoryMethod(): Product {
- return ConcreteProduct()
- }
- }
复制代码 1.3 抽象工厂模式 (Abstract Factory)
目标: 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
Java 实现:
- interface AbstractFactory {
- ProductA createProductA();
- ProductB createProductB();
- }
- class ConcreteFactory1 implements AbstractFactory {
- @Override
- public ProductA createProductA() {
- return new ConcreteProductA1();
- }
- @Override
- public ProductB createProductB() {
- return new ConcreteProductB1();
- }
- }
- class ConcreteFactory2 implements AbstractFactory {
- @Override
- public ProductA createProductA() {
- return new ConcreteProductA2();
- }
- @Override
- public ProductB createProductB() {
- return new ConcreteProductB2();
- }
- }
复制代码 Kotlin 实现:
- interface AbstractFactory {
- fun createProductA(): ProductA
- fun createProductB(): ProductB
- }
- class ConcreteFactory1 : AbstractFactory {
- override fun createProductA(): ProductA {
- return ConcreteProductA1()
- }
- override fun createProductB(): ProductB {
- return ConcreteProductB1()
- }
- }
- class ConcreteFactory2 : AbstractFactory {
- override fun createProductA(): ProductA {
- return ConcreteProductA2()
- }
- override fun createProductB(): ProductB {
- return ConcreteProductB2()
- }
- }
复制代码 1.4 建造者模式 (Builder)
目标: 将一个复杂对象的构建与其体现分离,使得同样的构建过程可以创建不同的体现。
Java 实现:
- class Product {
- private String partA;
- private String partB;
- public void setPartA(String partA) {
- this.partA = partA;
- }
- public void setPartB(String partB) {
- this.partB = partB;
- }
- @Override
- public String toString() {
- return "Product{partA='" + partA + "', partB='" + partB + "'}";
- }
- }
- interface Builder {
- void buildPartA();
- void buildPartB();
- Product getResult();
- }
- class ConcreteBuilder implements Builder {
- private Product product = new Product();
- @Override
- public void buildPartA() {
- product.setPartA("PartA");
- }
- @Override
- public void buildPartB() {
- product.setPartB("PartB");
- }
- @Override
- public Product getResult() {
- return product;
- }
- }
- class Director {
- private Builder builder;
- public Director(Builder builder) {
- this.builder = builder;
- }
- public void construct() {
- builder.buildPartA();
- builder.buildPartB();
- }
- }
复制代码 Kotlin 实现:
- class Product {
- var partA: String = ""
- var partB: String = ""
- override fun toString(): String {
- return "Product(partA='$partA', partB='$partB')"
- }
- }
- interface Builder {
- fun buildPartA()
- fun buildPartB()
- fun getResult(): Product
- }
- class ConcreteBuilder : Builder {
- private val product = Product()
- override fun buildPartA() {
- product.partA = "PartA"
- }
- override fun buildPartB() {
- product.partB = "PartB"
- }
- override fun getResult(): Product {
- return product
- }
- }
- class Director(private val builder: Builder) {
- fun construct() {
- builder.buildPartA()
- builder.buildPartB()
- }
- }
复制代码 1.5 原型模式 (Prototype)
目标: 通过复制现有对象来创建新对象,而不是通过新建类。
Java 实现:
- interface Prototype {
- Prototype clone();
- }
- class ConcretePrototype implements Prototype {
- private String field;
- public ConcretePrototype(String field) {
- this.field = field;
- }
- @Override
- public Prototype clone() {
- return new ConcretePrototype(this.field);
- }
- @Override
- public String toString() {
- return "ConcretePrototype{field='" + field + "'}";
- }
- }
复制代码 Kotlin 实现:
- interface Prototype {
- fun clone(): Prototype
- }
- class ConcretePrototype(private val field: String) : Prototype {
- override fun clone(): Prototype {
- return ConcretePrototype(field)
- }
- override fun toString(): String {
- return "ConcretePrototype(field='$field')"
- }
- }
复制代码 2. 结构型模式
2.1 适配器模式 (Adapter)
目标: 将一个类的接口转换成客户盼望的另一个接口。
Java 实现:
- interface Target {
- void request();
- }
- class Adaptee {
- public void specificRequest() {
- System.out.println("Specific request");
- }
- }
- class Adapter implements Target {
- private Adaptee adaptee;
- public Adapter(Adaptee adaptee) {
- this.adaptee = adaptee;
- }
- @Override
- public void request() {
- adaptee.specificRequest();
- }
- }
复制代码 Kotlin 实现:
- interface Target {
- fun request()
- }
- class Adaptee {
- fun specificRequest() {
- println("Specific request")
- }
- }
- class Adapter(private val adaptee: Adaptee) : Target {
- override fun request() {
- adaptee.specificRequest()
- }
- }
复制代码 2.2 桥接模式 (Bridge)
目标: 将抽象部分与实现部分分离,使它们可以独立厘革。
Java 实现:
- interface Implementor {
- void operationImpl();
- }
- class ConcreteImplementorA implements Implementor {
- @Override
- public void operationImpl() {
- System.out.println("ConcreteImplementorA operation");
- }
- }
- class ConcreteImplementorB implements Implementor {
- @Override
- public void operationImpl() {
- System.out.println("ConcreteImplementorB operation");
- }
- }
- abstract class Abstraction {
- protected Implementor implementor;
- public Abstraction(Implementor implementor) {
- this.implementor = implementor;
- }
- public abstract void operation();
- }
- class RefinedAbstraction extends Abstraction {
- public RefinedAbstraction(Implementor implementor) {
- super(implementor);
- }
- @Override
- public void operation() {
- implementor.operationImpl();
- }
- }
复制代码 Kotlin 实现:
- interface Implementor {
- fun operationImpl()
- }
- class ConcreteImplementorA : Implementor {
- override fun operationImpl() {
- println("ConcreteImplementorA operation")
- }
- }
- class ConcreteImplementorB : Implementor {
- override fun operationImpl() {
- println("ConcreteImplementorB operation")
- }
- }
- abstract class Abstraction(protected val implementor: Implementor) {
- abstract fun operation()
- }
- class RefinedAbstraction(implementor: Implementor) : Abstraction(implementor) {
- override fun operation() {
- implementor.operationImpl()
- }
- }
复制代码 2.3 组合模式 (Composite)
目标: 将对象组合成树形结构以体现“部分-整体”的层次结构。
Java 实现:
- interface Component {
- void operation();
- }
- class Leaf implements Component {
- @Override
- public void operation() {
- System.out.println("Leaf operation");
- }
- }
- class Composite implements Component {
- private List<Component> children = new ArrayList<>();
- public void add(Component component) {
- children.add(component);
- }
- public void remove(Component component) {
- children.remove(component);
- }
- @Override
- public void operation() {
- for (Component component : children) {
- component.operation();
- }
- }
- }
复制代码 Kotlin 实现:
- interface Component {
- fun operation()
- }
- class Leaf : Component {
- override fun operation() {
- println("Leaf operation")
- }
- }
- class Composite : Component {
- private val children = mutableListOf<Component>()
- fun add(component: Component) {
- children.add(component)
- }
- fun remove(component: Component) {
- children.remove(component)
- }
- override fun operation() {
- for (component in children) {
- component.operation()
- }
- }
- }
复制代码 2.4 装饰器模式 (Decorator)
目标: 动态地给对象添加一些额外的职责。
Java 实现:
- interface Component {
- void operation();
- }
- class ConcreteComponent implements Component {
- @Override
- public void operation() {
- System.out.println("ConcreteComponent operation");
- }
- }
- abstract class Decorator implements Component {
- protected Component component;
- public Decorator(Component component) {
- this.component = component;
- }
- @Override
- public void operation() {
- component.operation();
- }
- }
- class ConcreteDecoratorA extends Decorator {
- public ConcreteDecoratorA(Component component) {
- super(component);
- }
- @Override
- public void operation() {
- super.operation();
- addedBehavior();
- }
- private void addedBehavior() {
- System.out.println("ConcreteDecoratorA added behavior");
- }
- }
- class ConcreteDecoratorB extends Decorator {
- public ConcreteDecoratorB(Component component) {
- super(component);
- }
- @Override
- public void operation() {
- super.operation();
- addedBehavior();
- }
- private void addedBehavior() {
- System.out.println("ConcreteDecoratorB added behavior");
- }
- }
复制代码 Kotlin 实现:
- interface Component {
- fun operation()
- }
- class ConcreteComponent : Component {
- override fun operation() {
- println("ConcreteComponent operation")
- }
- }
- abstract class Decorator(private val component: Component) : Component {
- override fun operation() {
- component.operation()
- }
- }
- class ConcreteDecoratorA(component: Component) : Decorator(component) {
- override fun operation() {
- super.operation()
- addedBehavior()
- }
- private fun addedBehavior() {
- println("ConcreteDecoratorA added behavior")
- }
- }
- class ConcreteDecoratorB(component: Component) : Decorator(component) {
- override fun operation() {
- super.operation()
- addedBehavior()
- }
- private fun addedBehavior() {
- println("ConcreteDecoratorB added behavior")
- }
- }
复制代码 2.5 外观模式 (Facade)
目标: 为子系统中的一组接口提供一个同一的接口。
Java 实现:
- class SubsystemA {
- public void operationA() {
- System.out.println("SubsystemA operation");
- }
- }
- class SubsystemB {
- public void operationB() {
- System.out.println("SubsystemB operation");
- }
- }
- class Facade {
- private SubsystemA subsystemA = new SubsystemA();
- private SubsystemB subsystemB = new SubsystemB();
- public void operation() {
- subsystemA.operationA();
- subsystemB.operationB();
- }
- }
复制代码 Kotlin 实现:
- class SubsystemA {
- fun operationA() {
- println("SubsystemA operation")
- }
- }
- class SubsystemB {
- fun operationB() {
- println("SubsystemB operation")
- }
- }
- class Facade {
- private val subsystemA = SubsystemA()
- private val subsystemB = SubsystemB()
- fun operation() {
- subsystemA.operationA()
- subsystemB.operationB()
- }
- }
复制代码 2.6 享元模式 (Flyweight)
目标: 运用共享技能有效地支持大量细粒度的对象。
Java 实现:
- class Flyweight {
- private String intrinsicState;
- public Flyweight(String intrinsicState) {
- this.intrinsicState = intrinsicState;
- }
- public void operation(String extrinsicState) {
- System.out.println("Intrinsic State = " + intrinsicState + ", Extrinsic State = " + extrinsicState);
- }
- }
- class FlyweightFactory {
- private Map<String, Flyweight> flyweights = new HashMap<>();
- public Flyweight getFlyweight(String key) {
- if (!flyweights.containsKey(key)) {
- flyweights.put(key, new Flyweight(key));
- }
- return flyweights.get(key);
- }
- }
复制代码 Kotlin 实现:
- class Flyweight(private val intrinsicState: String) {
- fun operation(extrinsicState: String) {
- println("Intrinsic State = $intrinsicState, Extrinsic State = $extrinsicState")
- }
- }
- class FlyweightFactory {
- private val flyweights = mutableMapOf<String, Flyweight>()
- fun getFlyweight(key: String): Flyweight {
- return flyweights.getOrPut(key) { Flyweight(key) }
- }
- }
复制代码 2.7 署理模式 (Proxy)
目标: 为其他对象提供一个署理以控制对这个对象的访问。
Java 实现:
- interface Subject {
- void request();
- }
- class RealSubject implements Subject {
- @Override
- public void request() {
- System.out.println("RealSubject request");
- }
- }
- class Proxy implements Subject {
- private RealSubject realSubject;
- @Override
- public void request() {
- if (realSubject == null) {
- realSubject = new RealSubject();
- }
- realSubject.request();
- }
- }
复制代码 Kotlin 实现:
- interface Subject {
- fun request()
- }
- class RealSubject : Subject {
- override fun request() {
- println("RealSubject request")
- }
- }
- class Proxy : Subject {
- private var realSubject: RealSubject? = null
- override fun request() {
- if (realSubject == null) {
- realSubject = RealSubject()
- }
- realSubject?.request()
- }
- }
复制代码 3. 举动型模式
3.1 责任链模式 (Chain of Responsibility)
目标: 使多个对象都有时机处置处罚请求,从而避免请求的发送者与吸收者之间的耦合。
Java 实现:
- abstract class Handler {
- protected Handler successor;
- public void setSuccessor(Handler successor) {
- this.successor = successor;
- }
- public abstract void handleRequest(String request);
- }
- class ConcreteHandlerA extends Handler {
- @Override
- public void handleRequest(String request) {
- if (request.equals("A")) {
- System.out.println("ConcreteHandlerA handles request");
- } else if (successor != null) {
- successor.handleRequest(request);
- }
- }
- }
- class ConcreteHandlerB extends Handler {
- @Override
- public void handleRequest(String request) {
- if (request.equals("B")) {
- System.out.println("ConcreteHandlerB handles request");
- } else if (successor != null) {
- successor.handleRequest(request);
- }
- }
- }
复制代码 Kotlin 实现:
- abstract class Handler {
- var successor: Handler? = null
- abstract fun handleRequest(request: String)
- }
- class ConcreteHandlerA : Handler() {
- override fun handleRequest(request: String) {
- if (request == "A") {
- println("ConcreteHandlerA handles request")
- } else {
- successor?.handleRequest(request)
- }
- }
- }
- class ConcreteHandlerB : Handler() {
- override fun handleRequest(request: String) {
- if (request == "B") {
- println("ConcreteHandlerB handles request")
- } else {
- successor?.handleRequest(request)
- }
- }
- }
复制代码 3.2 下令模式 (Command)
目标: 将请求封装为对象,从而使你可以用不同的请求对客户进行参数化。
Java 实现:
- interface Command {
- void execute();
- }
- class ConcreteCommand implements Command {
- private Receiver receiver;
- public ConcreteCommand(Receiver receiver) {
- this.receiver = receiver;
- }
- @Override
- public void execute() {
- receiver.action();
- }
- }
- class Receiver {
- public void action() {
- System.out.println("Receiver action");
- }
- }
- class Invoker {
- private Command command;
- public void setCommand(Command command) {
- this.command = command;
- }
- public void executeCommand() {
- command.execute();
- }
- }
复制代码 Kotlin 实现:
- interface Command {
- fun execute()
- }
- class ConcreteCommand(private val receiver: Receiver) : Command {
- override fun execute() {
- receiver.action()
- }
- }
- class Receiver {
- fun action() {
- println("Receiver action")
- }
- }
- class Invoker {
- private var command: Command? = null
- fun setCommand(command: Command) {
- this.command = command
- }
- fun executeCommand() {
- command?.execute()
- }
- }
复制代码 3.3 解释器模式 (Interpreter)
目标: 给定一个语言,定义它的文法的一种体现,并定义一个解释器,这个解释器使用该体现来解释语言中的句子。
Java 实现:
- class OrExpression implements Expression {
- private Expression expr1;
- private Expression expr2;
- public OrExpression(Expression expr1, Expression expr2) {
- this.expr1 = expr1;
- this.expr2 = expr2;
- }
- @Override
- public boolean interpret(String context) {
- return expr1.interpret(context) || expr2.interpret(context);
- }
- }
- class AndExpression implements Expression {
- private Expression expr1;
- private Expression expr2;
- public AndExpression(Expression expr1, Expression expr2) {
- this.expr1 = expr1;
- this.expr2 = expr2;
- }
- @Override
- public boolean interpret(String context) {
- return expr1.interpret(context) && expr2.interpret(context);
- }
- }
- // 使用示例
- public class InterpreterPatternDemo {
- public static void main(String[] args) {
- Expression isMale = new TerminalExpression("John");
- Expression isMarriedWoman = new AndExpression(new TerminalExpression("Julie"), new TerminalExpression("Married"));
- Expression isSingleOrMale = new OrExpression(isMale, new TerminalExpression("Single"));
- System.out.println("John is male? " + isMale.interpret("John"));
- System.out.println("Julie is a married woman? " + isMarriedWoman.interpret("Married Julie"));
- System.out.println("Is John single or male? " + isSingleOrMale.interpret("Single John"));
- }
- }
复制代码 Kotlin 实现:
- interface Expression {
- fun interpret(context: String): Boolean
- }
- class TerminalExpression(private val data: String) : Expression {
- override fun interpret(context: String): Boolean {
- return context.contains(data)
- }
- }
- class OrExpression(private val expr1: Expression, private val expr2: Expression) : Expression {
- override fun interpret(context: String): Boolean {
- return expr1.interpret(context) || expr2.interpret(context)
- }
- }
- class AndExpression(private val expr1: Expression, private val expr2: Expression) : Expression {
- override fun interpret(context: String): Boolean {
- return expr1.interpret(context) && expr2.interpret(context)
- }
- }
- // 使用示例
- fun main() {
- val isMale = TerminalExpression("John")
- val isMarriedWoman = AndExpression(TerminalExpression("Julie"), TerminalExpression("Married"))
- val isSingleOrMale = OrExpression(isMale, TerminalExpression("Single"))
- println("John is male? ${isMale.interpret("John")}")
- println("Julie is a married woman? ${isMarriedWoman.interpret("Married Julie")}")
- println("Is John single or male? ${isSingleOrMale.interpret("Single John")}")
- }
复制代码 3.4 迭代器模式 (Iterator)
目标: 提供一种方法序次访问一个聚合对象中的各个元素,而又不暴露其内部体现。
Java 实现:
- interface Iterator<T> {
- boolean hasNext();
- T next();
- }
- interface Container<T> {
- Iterator<T> getIterator();
- }
- class NameRepository implements Container<String> {
- private String[] names = {"John", "Julie", "Adam", "Eve"};
- @Override
- public Iterator<String> getIterator() {
- return new NameIterator();
- }
- private class NameIterator implements Iterator<String> {
- private int index;
- @Override
- public boolean hasNext() {
- return index < names.length;
- }
- @Override
- public String next() {
- if (hasNext()) {
- return names[index++];
- }
- return null;
- }
- }
- }
- // 使用示例
- public class IteratorPatternDemo {
- public static void main(String[] args) {
- NameRepository nameRepository = new NameRepository();
- Iterator<String> iterator = nameRepository.getIterator();
- while (iterator.hasNext()) {
- System.out.println("Name: " + iterator.next());
- }
- }
- }
复制代码 Kotlin 实现:
- interface Iterator<T> {
- fun hasNext(): Boolean
- fun next(): T
- }
- interface Container<T> {
- fun getIterator(): Iterator<T>
- }
- class NameRepository : Container<String> {
- private val names = arrayOf("John", "Julie", "Adam", "Eve")
- override fun getIterator(): Iterator<String> {
- return NameIterator()
- }
- private inner class NameIterator : Iterator<String> {
- private var index = 0
- override fun hasNext(): Boolean {
- return index < names.size
- }
- override fun next(): String {
- return if (hasNext()) {
- names[index++]
- } else {
- throw NoSuchElementException()
- }
- }
- }
- }
- // 使用示例
- fun main() {
- val nameRepository = NameRepository()
- val iterator = nameRepository.getIterator()
- while (iterator.hasNext()) {
- println("Name: ${iterator.next()}")
- }
- }
复制代码 3.5 中介者模式 (Mediator)
目标: 定义一个中介对象来封装一系列对象之间的交互,使它们不需要显式地相互引用。
Java 实现:
- interface Mediator {
- void send(String message, Colleague colleague);
- }
- abstract class Colleague {
- protected Mediator mediator;
- public Colleague(Mediator mediator) {
- this.mediator = mediator;
- }
- public abstract void send(String message);
- public abstract void receive(String message);
- }
- class ConcreteColleagueA extends Colleague {
- public ConcreteColleagueA(Mediator mediator) {
- super(mediator);
- }
- @Override
- public void send(String message) {
- mediator.send(message, this);
- }
- @Override
- public void receive(String message) {
- System.out.println("ConcreteColleagueA received: " + message);
- }
- }
- class ConcreteColleagueB extends Colleague {
- public ConcreteColleagueB(Mediator mediator) {
- super(mediator);
- }
- @Override
- public void send(String message) {
- mediator.send(message, this);
- }
- @Override
- public void receive(String message) {
- System.out.println("ConcreteColleagueB received: " + message);
- }
- }
- class ConcreteMediator implements Mediator {
- private ConcreteColleagueA colleagueA;
- private ConcreteColleagueB colleagueB;
- public void setColleagueA(ConcreteColleagueA colleagueA) {
- this.colleagueA = colleagueA;
- }
- public void setColleagueB(ConcreteColleagueB colleagueB) {
- this.colleagueB = colleagueB;
- }
- @Override
- public void send(String message, Colleague colleague) {
- if (colleague == colleagueA) {
- colleagueB.receive(message);
- } else {
- colleagueA.receive(message);
- }
- }
- }
- // 使用示例
- public class MediatorPatternDemo {
- public static void main(String[] args) {
- ConcreteMediator mediator = new ConcreteMediator();
- ConcreteColleagueA colleagueA = new ConcreteColleagueA(mediator);
- ConcreteColleagueB colleagueB = new ConcreteColleagueB(mediator);
- mediator.setColleagueA(colleagueA);
- mediator.setColleagueB(colleagueB);
- colleagueA.send("Hello from A");
- colleagueB.send("Hi from B");
- }
- }
复制代码 Kotlin 实现:
- interface Mediator {
- fun send(message: String, colleague: Colleague)
- }
- abstract class Colleague(protected val mediator: Mediator) {
- abstract fun send(message: String)
- abstract fun receive(message: String)
- }
- class ConcreteColleagueA(mediator: Mediator) : Colleague(mediator) {
- override fun send(message: String) {
- mediator.send(message, this)
- }
- override fun receive(message: String) {
- println("ConcreteColleagueA received: $message")
- }
- }
- class ConcreteColleagueB(mediator: Mediator) : Colleague(mediator) {
- override fun send(message: String) {
- mediator.send(message, this)
- }
- override fun receive(message: String) {
- println("ConcreteColleagueB received: $message")
- }
- }
- class ConcreteMediator : Mediator {
- private lateinit var colleagueA: ConcreteColleagueA
- private lateinit var colleagueB: ConcreteColleagueB
- fun setColleagueA(colleagueA: ConcreteColleagueA) {
- this.colleagueA = colleagueA
- }
- fun setColleagueB(colleagueB: ConcreteColleagueB) {
- this.colleagueB = colleagueB
- }
- override fun send(message: String, colleague: Colleague) {
- when (colleague) {
- colleagueA -> colleagueB.receive(message)
- else -> colleagueA.receive(message)
- }
- }
- }
- // 使用示例
- fun main() {
- val mediator = ConcreteMediator()
- val colleagueA = ConcreteColleagueA(mediator)
- val colleagueB = ConcreteColleagueB(mediator)
- mediator.setColleagueA(colleagueA)
- mediator.setColleagueB(colleagueB)
- colleagueA.send("Hello from A")
- colleagueB.send("Hi from B")
- }
复制代码 3.6 备忘录模式 (Memento)
目标: 在不粉碎封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
Java 实现:
- class Memento {
- private String state;
- public Memento(String state) {
- this.state = state;
- }
- public String getState() {
- return state;
- }
- }
- class Originator {
- private String state;
- public void setState(String state) {
- this.state = state;
- }
- public String getState() {
- return state;
- }
- public Memento saveStateToMemento() {
- return new Memento(state);
- }
- public void getStateFromMemento(Memento memento) {
- state = memento.getState();
- }
- }
- class CareTaker {
- private List<Memento> mementoList = new ArrayList<>();
- public void add(Memento state) {
- mementoList.add(state);
- }
- public Memento get(int index) {
- return mementoList.get(index);
- }
- }
- // 使用示例
- public class MementoPatternDemo {
- public static void main(String[] args) {
- Originator originator = new Originator();
- CareTaker careTaker = new CareTaker();
- originator.setState("State #1");
- careTaker.add(originator.saveStateToMemento());
- originator.setState("State #2");
- careTaker.add(originator.saveStateToMemento());
- originator.setState("State #3");
- careTaker.add(originator.saveStateToMemento());
- System.out.println("Current State: " + originator.getState());
- originator.getStateFromMemento(careTaker.get(0));
- System.out.println("First saved State: " + originator.getState());
- originator.getStateFromMemento(careTaker.get(1));
- System.out.println("Second saved State: " + originator.getState());
- }
- }
复制代码 Kotlin 实现:
- class Memento(val state: String)
- class Originator {
- private var state: String = ""
- fun setState(state: String) {
- this.state = state
- }
- fun getState(): String {
- return state
- }
- fun saveStateToMemento(): Memento {
- return Memento(state)
- }
- fun getStateFromMemento(memento: Memento) {
- state = memento.state
- }
- }
- class CareTaker {
- private val mementoList = mutableListOf<Memento>()
- fun add(state: Memento) {
- mementoList.add(state)
- }
- fun get(index: Int): Memento {
- return mementoList[index]
- }
- }
- // 使用示例
- fun main() {
- val originator = Originator()
- val careTaker = CareTaker()
- originator.setState("State #1")
- careTaker.add(originator.saveStateToMemento())
- originator.setState("State #2")
- careTaker.add(originator.saveStateToMemento())
- originator.setState("State #3")
- careTaker.add(originator.saveStateToMemento())
- println("Current State: ${originator.getState()}")
- originator.getStateFromMemento(careTaker.get(0))
- println("First saved State: ${originator.getState()}")
- originator.getStateFromMemento(careTaker.get(1))
- println("Second saved State: ${originator.getState()}")
- }
复制代码 3.7 观察者模式 (Observer)
目标: 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,全部依赖于它的对象都得到通知并被自动更新。
Java 实现:
- interface Observer {
- void update(String message);
- }
- class ConcreteObserver implements Observer {
- private String name;
- public ConcreteObserver(String name) {
- this.name = name;
- }
- @Override
- public void update(String message) {
- System.out.println(name + " received message: " + message);
- }
- }
- class Subject {
- private List<Observer> observers = new ArrayList<>();
- private String state;
- public void setState(String state) {
- this.state = state;
- notifyAllObservers();
- }
- public void attach(Observer observer) {
- observers.add(observer);
- }
- public void notifyAllObservers() {
- for (Observer observer : observers) {
- observer.update(state);
- }
- }
- }
- // 使用示例
- public class ObserverPatternDemo {
- public static void main(String[] args) {
- Subject subject = new Subject();
- Observer observer1 = new ConcreteObserver("Observer 1");
- Observer observer2 = new ConcreteObserver("Observer 2");
- subject.attach(observer1);
- subject.attach(observer2);
- subject.setState("State #1");
- subject.setState("State #2");
- }
- }
复制代码 Kotlin 实现:
- interface Observer {
- fun update(message: String)
- }
- class ConcreteObserver(private val name: String) : Observer {
- override fun update(message: String) {
- println("$name received message: $message")
- }
- }
- class Subject {
- private val observers = mutableListOf<Observer>()
- private var state: String = ""
- fun setState(state: String) {
- this.state = state
- notifyAllObservers()
- }
- fun attach(observer: Observer) {
- observers.add(observer)
- }
- private fun notifyAllObservers() {
- for (observer in observers) {
- observer.update(state)
- }
- }
- }
- // 使用示例
- fun main() {
- val subject = Subject()
- val observer1 = ConcreteObserver("Observer 1")
- val observer2 = ConcreteObserver("Observer 2")
- subject.attach(observer1)
- subject.attach(observer2)
- subject.setState("State #1")
- subject.setState("State #2")
- }
复制代码 3.8 状态模式 (State)
目标: 允许一个对象在其内部状态改变时改变它的举动。
Java 实现:
- interface State {
- void handle(Context context);
- }
- class ConcreteStateA implements State {
- @Override
- public void handle(Context context) {
- System.out.println("Handling in State A");
- context.setState(new ConcreteStateB());
- }
- }
- class ConcreteStateB implements State {
- @Override
- public void handle(Context context) {
- System.out.println("Handling in State B");
- context.setState(new ConcreteStateA());
- }
- }
- class Context {
- private State state;
- public Context(State state) {
- this.state = state;
- }
- public void setState(State state) {
- this.state = state;
- }
- public void request() {
- state.handle(this);
- }
- }
- // 使用示例
- public class StatePatternDemo {
- public static void main(String[] args) {
- Context context = new Context(new ConcreteStateA());
- context.request();
- context.request();
- context.request();
- }
- }
复制代码 Kotlin 实现:
- interface State {
- fun handle(context: Context)
- }
- class ConcreteStateA : State {
- override fun handle(context: Context) {
- println("Handling in State A")
- context.setState(ConcreteStateB())
- }
- }
- class ConcreteStateB : State {
- override fun handle(context: Context) {
- println("Handling in State B")
- context.setState(ConcreteStateA())
- }
- }
- class Context(private var state: State) {
- fun setState(state: State) {
- this.state = state
- }
- fun request() {
- state.handle(this)
- }
- }
- // 使用示例
- fun main() {
- val context = Context(ConcreteStateA())
- context.request()
- context.request()
- context.request()
- }
复制代码 3.9 计谋模式 (Strategy)
目标: 定义一系列算法,将它们封装起来,并且使它们可以相互更换。
Java 实现:
- interface Strategy {
- int doOperation(int num1, int num2);
- }
- class OperationAdd implements Strategy {
- @Override
- public int doOperation(int num1, int num2) {
- return num1 + num2;
- }
- }
- class OperationSubtract implements Strategy {
- @Override
- public int doOperation(int num1, int num2) {
- return num1 - num2;
- }
- }
- class OperationMultiply implements Strategy {
- @Override
- public int doOperation(int num1, int num2) {
- return num1 * num2;
- }
- }
- class Context {
- private Strategy strategy;
- public Context(Strategy strategy) {
- this.strategy = strategy;
- }
- public int executeStrategy(int num1, int num2) {
- return strategy.doOperation(num1, num2);
- }
- }
- // 使用示例
- public class StrategyPatternDemo {
- public static void main(String[] args) {
- Context context = new Context(new OperationAdd());
- System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
- context = new Context(new OperationSubtract());
- System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
- context = new Context(new OperationMultiply());
- System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
- }
- }
复制代码 Kotlin 实现:
- interface Strategy {
- fun doOperation(num1: Int, num2: Int): Int
- }
- class OperationAdd : Strategy {
- override fun doOperation(num1: Int, num2: Int): Int {
- return num1 + num2
- }
- }
- class OperationSubtract : Strategy {
- override fun doOperation(num1: Int, num2: Int): Int {
- return num1 - num2
- }
- }
- class OperationMultiply : Strategy {
- override fun doOperation(num1: Int, num2: Int): Int {
- return num1 * num2
- }
- }
- class Context(private var strategy: Strategy) {
- fun executeStrategy(num1: Int, num2: Int): Int {
- return strategy.doOperation(num1, num2)
- }
- }
- // 使用示例
- fun main() {
- var context = Context(OperationAdd())
- println("10 + 5 = ${context.executeStrategy(10, 5)}")
- context = Context(OperationSubtract())
- println("10 - 5 = ${context.executeStrategy(10, 5)}")
- context = Context(OperationMultiply())
- println("10 * 5 = ${context.executeStrategy(10, 5)}")
- }
复制代码 3.10 模板方法模式 (Template Method)
目标: 定义一个操作中的算法骨架,而将一些步骤延迟到子类中。
Java 实现:
- abstract class Game {
- abstract void initialize();
- abstract void startPlay();
- abstract void endPlay();
- // 模板方法
- public final void play() {
- initialize();
- startPlay();
- endPlay();
- }
- }
- class Cricket extends Game {
- @Override
- void initialize() {
- System.out.println("Cricket Game Initialized!");
- }
- @Override
- void startPlay() {
- System.out.println("Cricket Game Started!");
- }
- @Override
- void endPlay() {
- System.out.println("Cricket Game Finished!");
- }
- }
- class Football extends Game {
- @Override
- void initialize() {
- System.out.println("Football Game Initialized!");
- }
- @Override
- void startPlay() {
- System.out.println("Football Game Started!");
- }
- @Override
- void endPlay() {
- System.out.println("Football Game Finished!");
- }
- }
- // 使用示例
- public class TemplateMethodPatternDemo {
- public static void main(String[] args) {
- Game game = new Cricket();
- game.play();
- game = new Football();
- game.play();
- }
- }
复制代码 Kotlin 实现:
- abstract class Game {
- abstract fun initialize()
- abstract fun startPlay()
- abstract fun endPlay()
- // 模板方法
- fun play() {
- initialize()
- startPlay()
- endPlay()
- }
- }
- class Cricket : Game() {
- override fun initialize() {
- println("Cricket Game Initialized!")
- }
- override fun startPlay() {
- println("Cricket Game Started!")
- }
- override fun endPlay() {
- println("Cricket Game Finished!")
- }
- }
- class Football : Game() {
- override fun initialize() {
- println("Football Game Initialized!")
- }
- override fun startPlay() {
- println("Football Game Started!")
- }
- override fun endPlay() {
- println("Football Game Finished!")
- }
- }
- // 使用示例
- fun main() {
- var game: Game = Cricket()
- game.play()
- game = Football()
- game.play()
- }
复制代码 3.11 访问者模式 (Visitor)
目标: 体现一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
Java 实现:
- interface ComputerPartVisitor {
- void visit(Computer computer);
- void visit(Mouse mouse);
- void visit(Keyboard keyboard);
- void visit(Monitor monitor);
- }
- interface ComputerPart {
- void accept(ComputerPartVisitor computerPartVisitor);
- }
- class Keyboard implements ComputerPart {
- @Override
- public void accept(ComputerPartVisitor computerPartVisitor) {
- computerPartVisitor.visit(this);
- }
- }
- class Monitor implements ComputerPart {
- @Override
- public void accept(ComputerPartVisitor computerPartVisitor) {
- computerPartVisitor.visit(this);
- }
- }
- class Mouse implements ComputerPart {
- @Override
- public void accept(ComputerPartVisitor computerPartVisitor) {
- computerPartVisitor.visit(this);
- }
- }
- class Computer implements ComputerPart {
- ComputerPart[] parts;
- public Computer() {
- parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
- }
- @Override
- public void accept(ComputerPartVisitor computerPartVisitor) {
- for (ComputerPart part : parts) {
- part.accept(computerPartVisitor);
- }
- computerPartVisitor.visit(this);
- }
- }
- class ComputerPartDisplayVisitor implements ComputerPartVisitor {
- @Override
- public void visit(Computer computer) {
- System.out.println("Displaying Computer.");
- }
- @Override
- public void visit(Mouse mouse) {
- System.out.println("Displaying Mouse.");
- }
- @Override
- public void visit(Keyboard keyboard) {
- System.out.println("Displaying Keyboard.");
- }
- @Override
- public void visit(Monitor monitor) {
- System.out.println("Displaying Monitor.");
- }
- }
- // 使用示例
- public class VisitorPatternDemo {
- public static void main(String[] args) {
- ComputerPart computer = new Computer();
- computer.accept(new ComputerPartDisplayVisitor());
- }
- }
复制代码 Kotlin 实现:
- interface ComputerPartVisitor {
- fun visit(computer: Computer)
- fun visit(mouse: Mouse)
- fun visit(keyboard: Keyboard)
- fun visit(monitor: Monitor)
- }
- interface ComputerPart {
- fun accept(computerPartVisitor: ComputerPartVisitor)
- }
- class Keyboard : ComputerPart {
- override fun accept(computerPartVisitor: ComputerPartVisitor) {
- computerPartVisitor.visit(this)
- }
- }
- class Monitor : ComputerPart {
- override fun accept(computerPartVisitor: ComputerPartVisitor) {
- computerPartVisitor.visit(this)
- }
- }
- class Mouse : ComputerPart {
- override fun accept(computerPartVisitor: ComputerPartVisitor) {
- computerPartVisitor.visit(this)
- }
- }
- class Computer : ComputerPart {
- private val parts = arrayOf(Mouse(), Keyboard(), Monitor())
- override fun accept(computerPartVisitor: ComputerPartVisitor) {
- for (part in parts) {
- part.accept(computerPartVisitor)
- }
- computerPartVisitor.visit(this)
- }
- }
- class ComputerPartDisplayVisitor : ComputerPartVisitor {
- override fun visit(computer: Computer) {
- println("Displaying Computer.")
- }
- override fun visit(mouse: Mouse) {
- println("Displaying Mouse.")
- }
- override fun visit(keyboard: Keyboard) {
- println("Displaying Keyboard.")
- }
- override fun visit(monitor: Monitor) {
- println("Displaying Monitor.")
- }
- }
- // 使用示例
- fun main() {
- val computer = Computer()
- computer.accept(ComputerPartDisplayVisitor())
- }
复制代码 以上是 23 种设计模式的详细实现,涵盖了创建型、结构型和举动型模式。每种模式都提供了 Java 和 Kotlin 的实现示例,并附有简朴的使用示例。盼望这些内容能帮助你更好地理解设计模式,并在实际开发中机动运用!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |