怎样在实际项目中优雅地应用设计模式?

一、设计模式介绍

设计模式是解决特定类型问题的通用方案,它们帮助开发者在设计和实现系统时提高代码的可复用性、可维护性和可扩展性。

二、常用的设计模式有哪些?

  1. 策略模式

  2. 工厂模式

  3. 单例模式

  4. 代理模式

  5. 工厂方法模式

  6. 观察者模式

  7. 模板方法模式

  8. 适配器模式

下面是一些常用的设计模式,每个设计模式的解析和实现模板:

1. 单例模式 (Singleton Pattern)

解析

单例模式确保一个类只有一个实例,并提供一个全局访问点。

实现模板(JavaScript)
class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance;
    }
    Singleton.instance = this;
  }

  // 其他方法和属性
}

const instance1 = new Singleton();
const instance2 = new Singleton();

console.log(instance1 === instance2); // 输出: true

实现模板(Java)
public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // 私有构造函数
    }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

2. 工厂方法模式 (Factory Method Pattern)

解析

工厂方法模式定义一个创建对象的接口,但由子类决定实例化哪个类。

实现模板(JavaScript)
class Product {
  use() {
    throw new Error('You have to implement the method use!');
  }
}

class ConcreteProductA extends Product {
  use() {
    console.log('Use product A');
  }
}

class ConcreteProductB extends Product {
  use() {
    console.log('Use product B');
  }
}

class Creator {
  factoryMethod() {
    // 子类会重写这个方法
    throw new Error('You have to implement the method factoryMethod!');
  }

  someOperation() {
    const product = this.factoryMethod();
    product.use();
  }
}

class ConcreteCreatorA extends Creator {
  factoryMethod() {
    return new ConcreteProductA();
  }
}

class ConcreteCreatorB extends Creator {
  factoryMethod() {
    return new ConcreteProductB();
  }
}

实现模板(Java)
public abstract class Product {
    public abstract void use();
}

public class ConcreteProductA extends Product {
    @Override
    public void use() {
        System.out.println("Use product A");
    }
}

public class ConcreteProductB extends Product {
    @Override
    public void use() {
        System.out.println("Use product B");
    }
}

public abstract class Creator {
    public abstract Product factoryMethod();

    public void someOperation() {
        Product product = factoryMethod();
        product.use();
    }
}

public class ConcreteCreatorA extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductA();
    }
}

public class ConcreteCreatorB extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductB();
    }
}

3. 观察者模式 (Observer Pattern)

解析

观察者模式定义了对象之间的一对多依赖关系,当一个对象状态发生变化时,所有依赖于它的对象都会收到通知并自动更新。

实现模板(JavaScript)
class Subject {
  constructor() {
    this.observers = [];
  }

  addObserver(observer) {
    this.observers.push(observer);
  }

  removeObserver(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }

  notifyObservers(data) {
    this.observers.forEach(observer => observer.update(data));
  }
}

class Observer {
  update(data) {
    console.log(`Received data: ${data}`);
  }
}

// 使用示例
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();

subject.addObserver(observer1);
subject.addObserver(observer2);

subject.notifyObservers('Some data'); // 两个观察者都会接收到通知

实现模板(Java)
import java.util.ArrayList;
import java.util.List;

interface Observer {
    void update(String data);
}

class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    public void notifyObservers(String data) {
        for (Observer observer : observers) {
            observer.update(data);
        }
    }
}

class ConcreteObserver implements Observer {
    @Override
    public void update(String data) {
        System.out.println("Received data: " + data);
    }
}

4. 策略模式 (Strategy Pattern)

解析

策略模式定义了一系列算法,把它们一个个封装起来,并使它们可以互相替换。此模式让算法的变化独立于使用算法的客户。

实现模板(JavaScript)
class StrategyA {
  execute() {
    console.log('Strategy A');
  }
}

class StrategyB {
  execute() {
    console.log('Strategy B');
  }
}

class Context {
  constructor(strategy) {
    this.strategy = strategy;
  }

  setStrategy(strategy) {
    this.strategy = strategy;
  }

  performOperation() {
    this.strategy.execute();
  }
}

// 使用示例
const context = new Context(new StrategyA());
context.performOperation(); // 输出: Strategy A
context.setStrategy(new StrategyB());
context.performOperation(); // 输出: Strategy B

实现模板(Java)
interface Strategy {
    void execute();
}

class StrategyA implements Strategy {
    @Override
    public void execute() {
        System.out.println("Strategy A");
    }
}

class StrategyB implements Strategy {
    @Override
    public void execute() {
        System.out.println("Strategy B");
    }
}

class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void performOperation() {
        strategy.execute();
    }
}

5. 装饰器模式 (Decorator Pattern)

解析

装饰器模式动态地给对象添加额外的职责。它提供了一种灵活的替代子类化的方法来扩展功能。

实现模板(JavaScript)
class Coffee {
  cost() {
    return 5;
  }
}

class MilkDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }

  cost() {
    return this.coffee.cost() + 2;
  }
}

class SugarDecorator {
  constructor(coffee) {
    this.coffee = coffee;
  }

  cost() {
    return this.coffee.cost() + 1;
  }
}

// 使用示例
let myCoffee = new Coffee();
myCoffee = new MilkDecorator(myCoffee);
myCoffee = new SugarDecorator(myCoffee);

console.log(myCoffee.cost()); // 输出: 8

实现模板(Java)
interface Coffee {
    int cost();
}

class SimpleCoffee implements Coffee {
    @Override
    public int cost() {
        return 5;
    }
}

class MilkDecorator implements Coffee {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public int cost() {
        return coffee.cost() + 2;
    }
}

class SugarDecorator implements Coffee {
    private Coffee coffee;

    public SugarDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public int cost() {
        return coffee.cost() + 1;
    }
}

6. 命令模式 (Command Pattern)

解析

命令模式将请求封装成对象,从而让你使用不同的请求、队列或操作日志来参数化客户端。

实现模板(JavaScript)
class Command {
  execute() {
    throw new Error('You have to implement the method execute!');
  }
}

class LightOnCommand extends Command {
  constructor(light) {
    super();
    this.light = light;
  }

  execute() {
    this.light.turnOn();
  }
}

class Light {
  turnOn() {
    console.log('Light is on');
  }
}

class RemoteControl {
  constructor(command) {
    this.command = command;
  }

  pressButton() {
    this.command.execute();
  }
}

// 使用示例
const light = new Light();
const lightOn = new LightOnCommand(light);
const remote = new RemoteControl(lightOn);

remote.pressButton(); // 输出: Light is on

实现模板(Java)
interface Command {
    void execute();
}

class Light {
    public void turnOn() {
        System.out.println("Light is on");
    }
}

class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }
}

class RemoteControl {
    private Command command;

    public RemoteControl(Command command) {
        this.command = command;
    }

    public void pressButton() {
        command.execute();
    }
}

7. 适配器模式 (Adapter Pattern)

解析

适配器模式将一个类的接口转换成客户端期望的另一种接口。适配器模式使得原本因接口不兼容而不能一起工作的类可以一起工作。

实现模板(JavaScript)
class OldSystem {
  oldMethod() {
    return 'Old method';
  }
}

class NewSystem {
  newMethod() {
    return 'New method';
  }
}

class Adapter {
  constructor(newSystem) {
    this.newSystem = newSystem;
  }

  oldMethod() {
    return this.newSystem.newMethod();
  }
}

// 使用示例
const newSystem = new NewSystem();
const adapter = new Adapter(newSystem);

console.log(adapter.oldMethod()); // 输出: New method

实现模板(Java)
interface OldSystem {
    String oldMethod();
}

class NewSystem {
    public String newMethod() {
        return "New method";
    }
}

class Adapter implements OldSystem {
    private NewSystem newSystem;

    public Adapter(NewSystem newSystem) {
        this.newSystem = newSystem;
    }

    @Override
    public String oldMethod() {
        return newSystem.newMethod();
    }
}

这些设计模式是软件设计中最常用的模式之一,可以帮助我们以更灵活和可维护的方式构建应用程序。每种模式有其特定的使用场景和优缺点,选择合适的模式能显著提升代码质量和开发效率。如果你对这些模式有更具体的应用场景或需求,欢迎继续提问!

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值