Java中的设计模式实现与应用

美食旅行家 2019-11-02 ⋅ 12 阅读

设计模式是一套被广泛应用于软件开发中的编程技巧和抽象概念。它们能够帮助开发者解决常见的设计问题,提高代码的可重用性、可维护性和可扩展性。在Java中,有许多经典的设计模式可供选择和实现。

1. 创建型设计模式

1.1 工厂模式(Factory Pattern)

工厂模式提供了一种创建对象的接口,但实际的对象创建过程由具体的工厂类来完成。这样可以将对象的创建与使用分离,使得代码更加灵活和可复用。

public interface Shape {
    void draw();
}

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

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

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

public class Main {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape circle = shapeFactory.createShape("Circle");
        circle.draw();
    }
}

1.2 单例模式(Singleton Pattern)

单例模式确保一个类只有一个实例,并提供一个全局的访问点。通过限制类的实例化,可以控制对象的个数,减少内存开销。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
    }
}

2. 结构型设计模式

2.1 适配器模式(Adapter Pattern)

适配器模式允许已存在的类与新的接口进行协作。它通过创建一个适配器类,将新接口转换为已存在的类所期望的接口。

public interface MediaPlayer {
    void play(String audioType, String filename);
}

public interface AdvancedMediaPlayer {
    void playVlc(String filename);
    void playMp4(String filename);
}

public class VlcPlayer implements AdvancedMediaPlayer {
    @Override
    public void playVlc(String filename) {
        System.out.println("Playing vlc file: " + filename);
    }

    @Override
    public void playMp4(String filename) {
        // Empty method
    }
}

public class Mp4Player implements AdvancedMediaPlayer {
    @Override
    public void playVlc(String filename) {
        // Empty method
    }

    @Override
    public void playMp4(String filename) {
        System.out.println("Playing mp4 file: " + filename);
    }
}

public class MediaAdapter implements MediaPlayer {
    private AdvancedMediaPlayer player;

    public MediaAdapter(String audioType) {
        if (audioType.equalsIgnoreCase("vlc")) {
            player = new VlcPlayer();
        } else if (audioType.equalsIgnoreCase("mp4")) {
            player = new Mp4Player();
        }
    }

    @Override
    public void play(String audioType, String filename) {
        if (audioType.equalsIgnoreCase("vlc")) {
            player.playVlc(filename);
        } else if (audioType.equalsIgnoreCase("mp4")) {
            player.playMp4(filename);
        }
    }
}

public class AudioPlayer implements MediaPlayer {
    private MediaAdapter mediaAdapter;

    @Override
    public void play(String audioType, String filename) {
        if (audioType.equalsIgnoreCase("mp3")) {
            System.out.println("Playing mp3 file: " + filename);
        } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
            mediaAdapter = new MediaAdapter(audioType);
            mediaAdapter.play(audioType, filename);
        } else {
            System.out.println("Invalid media type: " + audioType);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        AudioPlayer audioPlayer = new AudioPlayer();
        audioPlayer.play("mp3", "audio.mp3");
        audioPlayer.play("vlc", "video.vlc");
        audioPlayer.play("mp4", "video.mp4");
    }
}

2.2 装饰器模式(Decorator Pattern)

装饰器模式允许变更已存在的对象的行为。它通过创建一个装饰器类,将对象包装在其中,并在调用对象的方法前后添加额外的功能。

public interface Shape {
    void draw();
}

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

public abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }

    @Override
    public void draw() {
        decoratedShape.draw();
    }
}

public class RedShapeDecorator extends ShapeDecorator {
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }

    @Override
    public void draw() {
        decoratedShape.draw();
        setRedBorder();
    }

    private void setRedBorder() {
        System.out.println("Add red border.");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape redCircle = new RedShapeDecorator(new Circle());
        
        circle.draw();
        System.out.println("---");
        redCircle.draw();
    }
}

3. 行为型设计模式

3.1 观察者模式(Observer Pattern)

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

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

public interface Observer {
    void update();
}

public class ConcreteObserver implements Observer {
    @Override
    public void update() {
        System.out.println("Update notification received.");
    }
}

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

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

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

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

public class Main {
    public static void main(String[] args) {
        Subject subject = new Subject();
        Observer observer = new ConcreteObserver();

        subject.attach(observer);
        subject.notifyObservers();
        subject.detach(observer);
    }
}

3.2 策略模式(Strategy Pattern)

策略模式允许在运行时选择算法族中的一个。它将算法的使用与算法的实现分离,使得算法的变化不影响到使用算法的客户端。

public interface Strategy {
    void execute();
}

public class ConcreteStrategy1 implements Strategy {
    @Override
    public void execute() {
        System.out.println("Executing strategy 1.");
    }
}

public class ConcreteStrategy2 implements Strategy {
    @Override
    public void execute() {
        System.out.println("Executing strategy 2.");
    }
}

public class Context {
    private Strategy strategy;

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

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

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

public class Main {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStrategy1());
        context.executeStrategy();

        context.setStrategy(new ConcreteStrategy2());
        context.executeStrategy();
    }
}

以上只是Java中一些常见的设计模式的实现和应用示例。设计模式是一种重要的编程思想,能够帮助开发者写出更优雅、可维护和可扩展的代码。在实际开发中,根据具体的需求选择合适的设计模式可以大大提高开发效率和软件质量。


全部评论: 0

    我有话说: