使用Java实现设计模式

D
dashi35 2022-12-05T19:58:42+08:00
0 0 176

设计模式是对软件设计中常见问题解决方案的一种描述,可以帮助开发人员更好地组织和管理代码,提高代码的可重用性和可维护性。Java作为一种面向对象的编程语言,有丰富的设计模式支持。本文将介绍一些常见的设计模式,并使用Java语言进行演示实现。

1. 创建型设计模式

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

工厂方法模式是一种常见的创建型设计模式,它通过定义一个创建对象的接口,但具体的对象创建由子类决定。在Java中,我们可以使用接口或抽象类来定义对象的创建接口,然后由具体实现类负责实际的对象创建。

public interface Shape {
    void draw();
}

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

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

public interface ShapeFactory {
    Shape createShape();
}

public class CircleFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Circle();
    }
}

public class RectangleFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Rectangle();
    }
}

public class Main {
    public static void main(String[] args) {
        ShapeFactory circleFactory = new CircleFactory();
        Shape circle = circleFactory.createShape();
        circle.draw();
        
        ShapeFactory rectangleFactory = new RectangleFactory();
        Shape rectangle = rectangleFactory.createShape();
        rectangle.draw();
    }
}

1.2. 抽象工厂模式(Abstract Factory Pattern)

抽象工厂模式是一种更高级的工厂模式,它允许客户端使用抽象接口来创建一组相关或依赖的对象。在Java中,我们可以通过定义抽象工厂接口和具体工厂实现类来实现抽象工厂模式。

public interface Shape {
    void draw();
}

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

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

public interface ShapeFactory {
    Shape createShape();
}

public class SimpleShapeFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Circle();
    }
}

public class ComplexShapeFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Rectangle();
    }
}

public class Main {
    public static void main(String[] args) {
        ShapeFactory simpleFactory = new SimpleShapeFactory();
        Shape simpleShape = simpleFactory.createShape();
        simpleShape.draw();
        
        ShapeFactory complexFactory = new ComplexShapeFactory();
        Shape complexShape = complexFactory.createShape();
        complexShape.draw();
    }
}

2. 结构型设计模式

2.1. 适配器模式(Adapter Pattern)

适配器模式用于将一个类的接口转换成客户端期望的另一个接口。在Java中,我们可以通过创建一个实现目标接口的适配器类,并在适配器类中调用被适配类的方法来实现适配器模式。

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. Name: " + fileName);
    }
    
    @Override
    public void playMp4(String fileName) {
        // do nothing
    }
}

public class Mp4Player implements AdvancedMediaPlayer {
    @Override
    public void playVlc(String fileName) {
        // do nothing
    }
    
    @Override
    public void playMp4(String fileName) {
        System.out.println("Playing mp4 file. Name: " + fileName);
    }
}

public class MediaAdapter implements MediaPlayer {
    private AdvancedMediaPlayer advancedMediaPlayer;
    
    public MediaAdapter(String audioType) {
        if (audioType.equalsIgnoreCase("vlc")) {
            advancedMediaPlayer = new VlcPlayer();
        } else if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer = new Mp4Player();
        }
    }
    
    @Override
    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("vlc")) {
            advancedMediaPlayer.playVlc(fileName);
        } else if (audioType.equalsIgnoreCase("mp4")) {
            advancedMediaPlayer.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. Name: " + fileName);
        } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
            mediaAdapter = new MediaAdapter(audioType);
            mediaAdapter.play(audioType, fileName);
        } else {
            System.out.println("Invalid media. " + audioType + " format not supported");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MediaPlayer audioPlayer = new AudioPlayer();
        audioPlayer.play("mp3", "Beyond the Horizon.mp3");
        audioPlayer.play("mp4", "Alone.mp4");
        audioPlayer.play("vlc", "Far Far Away.vlc");
        audioPlayer.play("avi", "Mind Me.avi");
    }
}

2.2. 装饰器模式(Decorator Pattern)

装饰器模式允许通过创建一个装饰器类,包装原始类的对象,以在不修改原始类的前提下,动态地扩展其功能。在Java中,我们可以通过创建一个实现了目标接口的装饰器类,将原始类的对象作为构造函数参数传递给装饰器类。

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Shape: 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(decoratedShape);
    }
    
    private void setRedBorder(Shape decoratedShape) {
        System.out.println("Border Color: Red");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle();
        
        Shape redCircle = new RedShapeDecorator(new Circle());
        Shape redRectangle = new RedShapeDecorator(new Rectangle());
        
        System.out.println("Circle with normal border:");
        circle.draw();
        
        System.out.println("Circle with red border:");
        redCircle.draw();
        
        System.out.println("Rectangle with red border:");
        redRectangle.draw();
    }
}

3. 行为型设计模式

3.1. 观察者模式(Observer Pattern)

观察者模式定义对象之间的一种一对多的关系,当一个对象状态发生改变时,其所有依赖对象都将收到通知并自动更新。在Java中,我们可以使用java.util.Observablejava.util.Observer接口来实现观察者模式。

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class Subject extends Observable {
    private List<Observer> observers = new ArrayList<>();
    private int state;
    
    public int getState() {
        return state;
    }
    
    public void setState(int state) {
        this.state = state;
        setChanged();
        notifyObservers();
    }
    
    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }
    
    @Override
    public void deleteObserver(Observer observer) {
        observers.remove(observer);
    }
    
    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(this, null);
        }
    }
}

public class BinaryObserver implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof Subject) {
            Subject subject = (Subject) o;
            System.out.println("Binary String: " + Integer.toBinaryString(subject.getState()));
        }
    }
}

public class OctalObserver implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof Subject) {
            Subject subject = (Subject) o;
            System.out.println("Octal String: " + Integer.toOctalString(subject.getState()));
        }
    }
}

public class HexObserver implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof Subject) {
            Subject subject = (Subject) o;
            System.out.println("Hex String: " + Integer.toHexString(subject.getState()));
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Subject subject = new Subject();
        
        new BinaryObserver().update(subject, null);
        new OctalObserver().update(subject, null);
        new HexObserver().update(subject, null);
        
        subject.addObserver(new BinaryObserver());
        subject.addObserver(new OctalObserver());
        subject.addObserver(new HexObserver());
        
        subject.setState(10);
    }
}

3.2. 策略模式(Strategy Pattern)

策略模式定义了一组算法,并将每个算法都封装起来,使它们可以互相替换。在Java中,我们可以通过创建策略接口和具体策略实现类,然后在需要使用算法的类中调用具体的策略对象来实现策略模式。

public interface Strategy {
    int doOperation(int num1, int num2);
}

public class AddStrategy implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

public class SubtractStrategy implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

public class MultiplyStrategy implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}

public 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 Main {
    public static void main(String[] args) {
        Context context = new Context(new AddStrategy());
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
        
        context = new Context(new SubtractStrategy());
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
        
        context = new Context(new MultiplyStrategy());
        System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
    }
}

以上仅介绍了一些常见的设计模式,每个设计模式都有其独特的用途和优缺点。通过合理应用设计模式,我们可以提高代码的可读性、可维护性和可扩展性。

相似文章

    评论 (0)