Structural patterns of design patterns and their corresponding codes: adapter pattern, decorator pattern, proxy pattern, appearance pattern, bridge pattern, combination pattern, flyweight pattern

structural pattern

Used to solve common problems in the relationship and organization of objects in system design. These patterns help us build more flexible, reusable, and maintainable software systems by defining interfaces, associations, aggregation, and inheritance relationships between different objects.

adapter mode

Function: Make classes that cannot work together originally due to incompatible interfaces work together.
The core idea of ​​the Adapter pattern is to introduce an adapter that acts as a bridge between two incompatible interfaces. The adapter implements the target interface expected by the client and contains internal references to the incompatible interface.

class adapter pattern

The class adapter pattern adapts one class to another interface through multiple inheritance. The adapter class inherits the target interface and at the same time inherits the adapted class, thereby linking the target interface and the adapted class. When the adapter class implements the target interface method, it calls the method of the adapted class to implement adaptation.

public interface Target {
    
    
    void request();
}

public class Adaptee {
    
    
    public void specificRequest() {
    
    
        System.out.println("Adaptee: specificRequest");
    }
}
// 创建适配器,同时继承被适配者的类,又实现目标接口,使二者建立联系
public class Adapter extends Adaptee implements Target {
    
    
    @Override
    public void request() {
    
    
        specificRequest();
    }
}

// 用户端使用适配器
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Target target = new Adapter();
        // request()方法调用了Adaptee类的specificRequest()方法
        // 从而来实现适配。
        target.request(); 
    }
}
object adapter pattern

The Object Adapter pattern adapts one class to another interface through composition. The adapter class contains an instance of the adapted class, and adaptation is achieved by calling methods of the adapted class.

public interface Target {
    
    
    void request();
}

public class Adaptee {
    
    
    public void specificRequest() {
    
    
        System.out.println("Adaptee: specificRequest");
    }
}

public class Adapter implements Target {
    
    
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
    
    
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
    
    
        adaptee.specificRequest();
    }
}

// 调用适配器
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        // 调用适配后的接口方法
        target.request(); 
    }
}

Decorator pattern

Function: Allows adding new functionality to an existing object without changing its structure.
Principle: A decorative class is created to wrap the original class and provide additional functions while maintaining the integrity of the class method signature.

// 抽象组件
public interface Component {
    
    
    void operation();
}

// 具体组件
public class ConcreteComponent implements Component {
    
    
    public void operation() {
    
    
        System.out.println("执行原始操作");
    }
}

// 抽象装饰器
public abstract class Decorator implements Component {
    
    
    protected Component component;

    public Decorator(Component component) {
    
    
        this.component = component;
    }

    public void operation() {
    
    
        component.operation();
    }
}

// 具体装饰器
public class ConcreteDecorator extends Decorator {
    
    
    public ConcreteDecorator(Component component) {
    
    
        super(component);
    }

    public void operation() {
    
    
        super.operation();
        // 增加新的行为
        addBehavior();
    }

    private void addBehavior() {
    
    
        System.out.println("执行额外行为");
    }
}

// 使用装饰器模式
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Component component = new ConcreteComponent();
        Component decoratedComponent = new ConcreteDecorator(component);
        decoratedComponent.operation();
    }
}

proxy mode

Function: Control access to actual objects through proxy objects.
Principle: The core is the proxy class, which implements the same interface as the actual object and holds a reference to the actual object. The proxy class is responsible for managing and controlling the actual object when calling, and can add additional logic before and after calling the method of the actual object.

// 抽象主题接口
interface Subject {
    
    
    void request();
}

// 真实主题
class RealSubject implements Subject {
    
    
    public void request() {
    
    
        System.out.println("执行真实主题的请求");
    }
}

// 代理类
class Proxy implements Subject {
    
    
    private RealSubject realSubject;

    public Proxy() {
    
    
        this.realSubject = new RealSubject();
    }

    public void request() {
    
    
        System.out.println("代理类处理请求");
        this.realSubject.request();
    }
}

// 使用代理模式
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Subject proxy = new Proxy();
        proxy.request();
    }
}

appearance mode

Function: Provides a simple and unified interface for complex subsystems, allowing the client to interact with the subsystem more conveniently, while also decoupling the subsystem from the client.
Principle: By introducing a appearance class, a set of related subsystem interfaces are encapsulated, and a high-level interface is provided for client use. The client only needs to interact with the appearance class and does not need to directly interact with multiple classes of the subsystem, thus simplifying the client's calling operation.

// 子系统类
class MusicPlayer {
    
    
    public void playSong(String song) {
    
    
        System.out.println("播放音乐:" + song);
    }
}

class VideoPlayer {
    
    
    public void playVideo(String video) {
    
    
        System.out.println("播放视频:" + video);
    }
}

class SubtitleDisplay {
    
    
    public void displaySubtitle(String video) {
    
    
        System.out.println("显示字幕:" + video);
    }
}

// 外观类
class AudioPlayer {
    
    
    private MusicPlayer musicPlayer;
    private VideoPlayer videoPlayer;
    private SubtitleDisplay subtitleDisplay;

    public AudioPlayer() {
    
    
        musicPlayer = new MusicPlayer();
        videoPlayer = new VideoPlayer();
        subtitleDisplay = new SubtitleDisplay();
    }

    // 对外提供的高层次接口
    public void playMusic(String song) {
    
    
        musicPlayer.playSong(song);
    }

    public void playVideo(String video) {
    
    
        videoPlayer.playVideo(video);
        subtitleDisplay.displaySubtitle(video);
    }
}

// 客户端代码
public class Client {
    
    
    public static void main(String[] args) {
    
    
        AudioPlayer audioPlayer = new AudioPlayer();
        // 直接通过外观调用
        audioPlayer.playMusic("Yesterday");
        audioPlayer.playVideo("Avatar");
    }
}

bridge mode

Function: Separate the abstract part from the implementation part so that they can change independently.
Principle: Create a bridge interface to decouple the abstract part and the implementation part. The abstract part calls the implementation part through the bridge interface, thus achieving the decoupling of abstraction and implementation, allowing them to be extended and changed independently.

// 抽象部分
abstract class Shape {
    
    
    protected DrawingAPI drawingAPI;

    protected Shape(DrawingAPI drawingAPI) {
    
    
        this.drawingAPI = drawingAPI;
    }

    public abstract void draw();
}

// 扩展抽象部分
class LineShape extends Shape {
    
    
    public LineShape(DrawingAPI drawingAPI) {
    
    
        super(drawingAPI);
    }

    public void draw() {
    
    
        System.out.println("绘制直线");
        drawingAPI.draw();
    }
}

class CircleShape extends Shape {
    
    
    public CircleShape(DrawingAPI drawingAPI) {
    
    
        super(drawingAPI);
    }

    public void draw() {
    
    
        System.out.println("绘制圆形");
        drawingAPI.draw();
    }
}

// 实现部分
interface DrawingAPI {
    
    
    void draw();
}

// 具体实现部分
class DirectXAPI implements DrawingAPI {
    
    
    public void draw() {
    
    
        System.out.println("使用DirectX绘图API");
    }
}

class OpenGLAPI implements DrawingAPI {
    
    
    public void draw() {
    
    
        System.out.println("使用OpenGL绘图API");
    }
}

// 使用桥接模式代码
public class Client {
    
    
    public static void main(String[] args) {
    
    
        DrawingAPI directx = new DirectXAPI();
        DrawingAPI opengl = new OpenGLAPI();

        Shape lineShape = new LineShape(directx);
        lineShape.draw();

        Shape circleShape = new CircleShape(opengl);
        circleShape.draw();
    }
}

Combination mode

Function: The combination mode allows the client to treat single objects and combined objects uniformly, so that users can use single objects and combined objects consistently, reducing the complexity of using the object tree structure.
Principle: component + leaf component + container component

// 实现一个文件系统的树形结构,包括文件和文件夹两种类型的节点:

// 组件接口
interface FileSystemComponent {
    
    
    void printStructure();
}

// 叶子组件:文件
class File implements FileSystemComponent {
    
    
    private String name;

    public File(String name) {
    
    
        this.name = name;
    }

    public void printStructure() {
    
    
        System.out.println("文件: " + name);
    }
}

// 容器组件:文件夹
class Folder implements FileSystemComponent {
    
    
    private String name;
    private List<FileSystemComponent> components;

    public Folder(String name) {
    
    
        this.name = name;
        components = new ArrayList<>();
    }

    public void addComponent(FileSystemComponent component) {
    
    
        components.add(component);
    }

    public void removeComponent(FileSystemComponent component) {
    
    
        components.remove(component);
    }

    public void printStructure() {
    
    
        System.out.println("文件夹: " + name);
        for (FileSystemComponent component : components) {
    
    
            component.printStructure();
        }
    }
}

// 使用组合模式
public class Client {
    
    
    public static void main(String[] args) {
    
    
        FileSystemComponent file1 = new File("file1.txt");
        FileSystemComponent file2 = new File("file2.txt");
        FileSystemComponent file3 = new File("file3.txt");

        FileSystemComponent folder1 = new Folder("folder1");
        folder1.addComponent(file1);
        folder1.addComponent(file2);

        FileSystemComponent folder2 = new Folder("folder2");
        folder2.addComponent(file3);

        FileSystemComponent root = new Folder("root");
        root.addComponent(folder1);
        root.addComponent(folder2);
        
        root.printStructure();
    }
}

Flyweight mode

Function: Improve system performance and reduce memory consumption by sharing objects.
Principle: Divide objects into shareable (internal state) and non-shareable (external state) parts, and reduce object creation and storage by sharing internal state.

// 抽象享元接口
interface ChessPiece {
    
    
    void draw(int x, int y);
}

// 具体享元类:白色棋子
class WhiteChessPiece implements ChessPiece {
    
    
    private String color;

    public WhiteChessPiece() {
    
    
        this.color = "白色";
    }

    public void draw(int x, int y) {
    
    
        System.out.println(color + "棋子,位置:(" + x + ", " + y + ")");
    }
}

// 具体享元类:黑色棋子
class BlackChessPiece implements ChessPiece {
    
    
    private String color;

    public BlackChessPiece() {
    
    
        this.color = "黑色";
    }

    public void draw(int x, int y) {
    
    
        System.out.println(color + "棋子,位置:(" + x + ", " + y + ")");
    }
}

// 享元工厂类
class ChessPieceFactory {
    
    
    private HashMap<String, ChessPiece> chessPieces;

    public ChessPieceFactory() {
    
    
        chessPieces = new HashMap<>();
    }

    public ChessPiece getChessPiece(String color) {
    
    
        if (chessPieces.containsKey(color)) {
    
    
            return chessPieces.get(color);
        } else {
    
    
            ChessPiece chessPiece;
            if (color.equals("白色")) {
    
    
                chessPiece = new WhiteChessPiece();
            } else {
    
    
                chessPiece = new BlackChessPiece();
            }
            chessPieces.put(color, chessPiece);
            return chessPiece;
        }
    }
}

// 使用享元模式
public class Client {
    
    
    public static void main(String[] args) {
    
    
        ChessPieceFactory factory = new ChessPieceFactory();

        ChessPiece whitePiece1 = factory.getChessPiece("白色");
        whitePiece1.draw(0, 0);

        ChessPiece blackPiece1 = factory.getChessPiece("黑色");
        blackPiece1.draw(0, 1);

        ChessPiece whitePiece2 = factory.getChessPiece("白色");
        whitePiece2.draw(1, 0);
        
        // 输出结果:
        // 白色棋子,位置:(0, 0)
        // 黑色棋子,位置:(0, 1)
        // 白色棋子,位置:(1, 0)
    }
}

Other design patterns and their codes

Creational design pattern

Guess you like

Origin blog.csdn.net/cleverstronge/article/details/131871217