设计模式直通车
发布人:shili8
发布时间:2025-01-04 11:14
阅读次数:0
**设计模式直通车**
设计模式是一套被反复使用多次的、经过实践证明良好的一般解决方案。它使我们能够抽象地描述一些基本概念,利用这些概念来实现系统的设计。设计模式可以帮助我们写出更好的代码,更容易维护和扩展。
**1. 单例模式**
Singleton(单例)模式是一种常见的设计模式,它确保一个类只有一个实例,并提供全局访问点。
javapublic class Singleton {
// 私有构造函数,防止外部直接创建对象 private Singleton() {}
// 静态变量,保存唯一的实例 private static Singleton instance = null;
// 公共方法,返回唯一的实例 public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
public void doSomething() {
System.out.println("Doing something...");
}
}
**2. 工厂模式**
Factory(工厂)模式是一种创建对象的方式,通过一个工厂类来创建多种类型的对象。
javapublic abstract class Animal {
public abstract void sound();
}
public class Dog extends Animal {
@Override public void sound() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override public void sound() {
System.out.println("Meow!");
}
}
public class AnimalFactory {
public static Animal createAnimal(String type) {
if (type.equals("dog")) {
return new Dog();
} else if (type.equals("cat")) {
return new Cat();
} else {
throw new RuntimeException("Invalid animal type");
}
}
public static void main(String[] args) {
Animal dog = createAnimal("dog");
Animal cat = createAnimal("cat");
dog.sound(); // Woof!
cat.sound(); // Meow!
}
}
**3. 观察者模式**
Observer(观察者)模式是一种设计模式,允许一个对象在另一个对象的状态改变时被通知。
javapublic interface Observer {
void update(String message);
}
public class WeatherStation {
private List observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
Observer observer1 = new Observer() {
@Override public void update(String message) {
System.out.println("Observer1: " + message);
}
};
Observer observer2 = new Observer() {
@Override public void update(String message) {
System.out.println("Observer2: " + message);
}
};
station.addObserver(observer1);
station.addObserver(observer2);
station.notifyObservers("Weather is sunny!"); // Observer1: Weather is sunny! Observer2: Weather is sunny!
}
}
**4. 策略模式**
Strategy(策略)模式是一种设计模式,允许在运行时动态地改变算法或行为。
javapublic interface Strategy {
void execute();
}
public class ConcreteStrategyA implements Strategy {
@Override public void execute() {
System.out.println("Executing strategy A");
}
}
public class ConcreteStrategyB implements Strategy {
@Override public void execute() {
System.out.println("Executing strategy B");
}
}
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
public static void main(String[] args) {
Context context = new Context();
context.setStrategy(new ConcreteStrategyA());
context.executeStrategy(); // Executing strategy A context.setStrategy(new ConcreteStrategyB());
context.executeStrategy(); // Executing strategy B }
}
**5. 模板方法模式**
Template Method(模板方法)模式是一种设计模式,定义一个算法的骨架,并允许子类重写某些步骤。
javapublic abstract class AbstractClass {
public final void templateMethod() {
step1();
step2();
step3();
}
protected void step1() {
System.out.println("Step1");
}
protected void step2() {
System.out.println("Step2");
}
protected abstract void step3();
public static void main(String[] args) {
AbstractClass concreteClass = new ConcreteClass();
concreteClass.templateMethod(); // Step1, Step2, Step3 }
}
public class ConcreteClass extends AbstractClass {
@Override protected void step3() {
System.out.println("Step3");
}
}
**6. 适配器模式**
Adapter(适配器)模式是一种设计模式,允许两个不兼容的接口之间进行通信。
javapublic interface TargetInterface {
void doSomething();
}
public class AdapteeClass implements AdapteeInterface {
@Override public void doSomethingElse() {
System.out.println("Doing something else");
}
}
public class AdapterClass extends AdapteeClass implements TargetInterface {
@Override public void doSomething() {
doSomethingElse();
}
public static void main(String[] args) {
TargetInterface target = new AdapterClass();
target.doSomething(); // Doing something else }
}
**7. 装饰器模式**
Decorator(装饰器)模式是一种设计模式,允许动态地添加或修改行为。
javapublic interface Component {
void doSomething();
}
public class ConcreteComponent implements Component {
@Override public void doSomething() {
System.out.println("Doing something");
}
}
public abstract class DecoratorClass implements Component {
protected Component component;
public DecoratorClass(Component component) {
this.component = component;
}
public void doSomething() {
component.doSomething();
}
}
public class ConcreteDecorator extends DecoratorClass {
public ConcreteDecorator(Component component) {
super(component);
}
@Override public void doSomething() {
System.out.println("Decorating...");
super.doSomething();
}
}
**8.享元模式**
Flyweight(享元)模式是一种设计模式,允许共享相同的状态。
javapublic interface Flyweight {
void operation(String state);
}
public class ConcreteFlyweight implements Flyweight {
private String state;
public ConcreteFlyweight(String state) {
this.state = state;
}
@Override public void operation(String state) {
System.out.println("State: " + state);
}
}
**9. 外观模式**
Facade(外观)模式是一种设计模式,允许简化复杂的接口。
javapublic interface FacadeInterface {
void doSomething();
}
public class ConcreteFacade implements FacadeInterface {
@Override public void doSomething() {
System.out.println("Doing something");
}
}
**10.代理模式**
Proxy(代理)模式是一种设计模式,允许为一个对象提供一个替代的实现。
javapublic interface ProxyInterface {
void doSomething();
}
public class ConcreteProxy implements ProxyInterface {
@Override public void doSomething() {
System.out.println("Doing something");
}
}
以上就是设计模式直通车的一些常见模式和示例。这些模式可以帮助你写出更好的代码,更容易维护和扩展。

