java架构师必懂的五种设计模式

本文通过实例展示了Java中的五种设计模式:单例模式创建唯一实例,工厂模式用于对象创建,观察者模式支持发布/订阅机制,策略模式定义算法的替换,装饰器模式动态添加行为。这些模式有助于提高代码的可扩展性和维护性。

1. 单例模式 (Singleton Pattern)

public class Singleton {
    private static Singleton instance;
    private Singleton() {
       // 私有构造方法
    }
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        // 使用单例对象进行操作
    }
}

2. 工厂模式 (Factory Pattern)

interface Shape {
    void draw();
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Draw a rectangle.");
    }
}

class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Draw a circle.");
    }
}

class ShapeFactory {
    public Shape createShape(String shapeType) {
        if (shapeType.equalsIgnoreCase("rectangle")) {
            return new Rectangle();
        } else if (shapeType.equalsIgnoreCase("circle")) {
            return new Circle();
        }
        return null;
    }
}

public class FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        
        Shape rectangle = shapeFactory.createShape("rectangle");
        rectangle.draw(); // 输出:Draw a rectangle.
        
        Shape circle = shapeFactory.createShape("circle");
        circle.draw(); // 输出:Draw a circle.
    }
}

3. 观察者模式 (Observer Pattern)

import java.util.ArrayList;
import java.util.List;

interface Observer {
    void update(String message);
}

class Subscriber implements Observer {
    private String name;
    
    public Subscriber(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        System.out.println(name + " received message: " + message);
    }
}

interface Subject {
    void attach(Observer observer);
    void detach(Observer observer);
    void notifyObservers(String message);
}

class Newsletter implements Subject {
    private List<Observer> subscribers = new ArrayList<>();
    
    @Override
    public void attach(Observer observer) {
        subscribers.add(observer);
    }
    
    @Override
    public void detach(Observer observer) {
        subscribers.remove(observer);
    }
    
    @Override
    public void notifyObservers(String message) {
        for (Observer observer : subscribers) {
            observer.update(message);
        }
    }
}

public class ObserverPatternDemo {
    public static void main(String[] args) {
        Newsletter newsletter = new Newsletter();
        
        Observer subscriber1 = new Subscriber("Subscriber1");
        Observer subscriber2 = new Subscriber("Subscriber2");
        
        newsletter.attach(subscriber1);
        newsletter.attach(subscriber2);
        
        newsletter.notifyObservers("New article published.");
        // 输出:
        // Subscriber1 received message: New article published.
        // Subscriber2 received message: New article published.
        
        newsletter.detach(subscriber2);
        
        newsletter.notifyObservers("Special promotion announced.");
        // 输出:
        // Subscriber1 received message: Special promotion announced.
    }
}

4. 策略模式 (Strategy Pattern)

interface SortStrategy {
    void sort(int[] arr);
}

class BubbleSortStrategy implements SortStrategy {
    @Override
    public void sort(int[] arr) {
        // 冒泡排序算法实现
        System.out.println("Bubble sort strategy applied.");
    }
}

class QuickSortStrategy implements SortStrategy {
    @Override
    public void sort(int[] arr) {
        // 快速排序算法实现
        System.out.println("Quick sort strategy applied.");
    }
}

class SortContext {
    private SortStrategy strategy;
    
    public void setStrategy(SortStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void performSort(int[] arr) {
        strategy.sort(arr);
    }
}

public class StrategyPatternDemo {
    public static void main(String[] args) {
        SortContext sortContext = new SortContext();
        
        int[] arr = {5, 2, 7, 1, 4};
        
        SortStrategy bubbleSortStrategy = new BubbleSortStrategy();
        sortContext.setStrategy(bubbleSortStrategy);
        sortContext.performSort(arr); // 输出:Bubble sort strategy applied.
        
        SortStrategy quickSortStrategy = new QuickSortStrategy();
        sortContext.setStrategy(quickSortStrategy);
        sortContext.performSort(arr); // 输出:Quick sort strategy applied.
    }
}

5. 装饰器模式 (Decorator Pattern)

interface Shape {
    void draw();
}

class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle.");
    }
}

abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;
    
    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }
    
    @Override
    public void draw() {
        decoratedShape.draw();
    }
}

class RedShapeDecorator extends ShapeDecorator {
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }
    
    @Override
    public void draw() {
        decoratedShape.draw();
        setRedBorder(decoratedShape);
    }
    
    private void setRedBorder(Shape decoratedShape) {
        System.out.println("Border color: Red");
    }
}

public class DecoratorPatternDemo {
    public static void main(String[] args) {
        Shape circle = new Circle();
        
        circle.draw(); // 输出:Drawing a circle.
        
        Shape redCircle = new RedShapeDecorator(new Circle());
        redCircle.draw();
        // 输出:
        // Drawing a circle.
        // Border color: Red
    }
}

以上代码示例展示了单例模式、工厂模式、观察者模式、策略模式和装饰器模式的用法。每个示例都包含了一个 main 函数来演示代码的用法。这些设计模式都是常见的、广泛应用于软件开发中的设计模式,可以提供可扩展、灵活和可维护的解决方案。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超维Ai编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值