디자인 패턴의 구조 패턴 및 해당 코드: 어댑터 패턴, 데코레이터 패턴, 프록시 패턴, 모양 패턴, 브리지 패턴, 조합 패턴, 플라이웨이트 패턴

구조적 패턴

시스템 설계에서 개체 관계 및 구성의 일반적인 문제를 해결하는 데 사용됩니다. 이러한 패턴은 다양한 개체 간의 인터페이스, 연결, 집계 및 상속 관계를 정의하여 보다 유연하고 재사용 가능하며 유지 관리 가능한 소프트웨어 시스템을 구축하는 데 도움이 됩니다.

어댑터 모드

기능: 호환되지 않는 인터페이스로 인해 원래 함께 작동할 수 없는 클래스를 함께 작동하도록 만듭니다.
어댑터 패턴의 핵심 아이디어는 호환되지 않는 두 인터페이스 사이의 브리지 역할을 하는 어댑터를 도입하는 것입니다. 어댑터는 클라이언트가 기대하는 대상 인터페이스를 구현하고 호환되지 않는 인터페이스에 대한 내부 참조를 포함합니다.

클래스 어댑터 패턴

클래스 어댑터 패턴은 다중 상속을 통해 한 클래스를 다른 인터페이스에 적용합니다. 어댑터 클래스는 대상 인터페이스를 상속함과 동시에 적응 클래스를 상속함으로써 대상 인터페이스와 적응 클래스를 연결합니다. 어댑터 클래스는 대상 인터페이스 메서드를 구현할 때 적응된 클래스의 메서드를 호출하여 적응을 구현합니다.

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(); 
    }
}
객체 어댑터 패턴

객체 어댑터 패턴은 구성을 통해 한 클래스를 다른 인터페이스에 적용합니다. 어댑터 클래스에는 적응된 클래스의 인스턴스가 포함되어 있으며 적응된 클래스의 메서드를 호출하여 적응이 이루어집니다.

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(); 
    }
}

데코레이터 패턴

기능: 구조를 변경하지 않고 기존 개체에 새 기능을 추가할 수 있습니다.
원리: 장식 클래스는 원래 클래스를 래핑하고 클래스 메서드 시그니처의 무결성을 유지하면서 추가 기능을 제공하기 위해 생성됩니다.

// 抽象组件
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 클래스는 호출 시 실제 객체에 대한 관리 및 제어를 담당하며, 실제 객체의 메소드 호출 전후에 추가적인 로직을 추가할 수 있습니다.

// 抽象主题接口
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();
    }
}

모양 모드

기능: 복잡한 하위 시스템에 대해 간단하고 통합된 인터페이스를 제공하여 클라이언트가 하위 시스템과 보다 편리하게 상호 작용할 수 있도록 하는 동시에 하위 시스템을 클라이언트에서 분리합니다.
원리: 모양 클래스를 도입함으로써 관련 하위 시스템 인터페이스 세트가 캡슐화되고 클라이언트 사용을 위한 상위 수준 인터페이스가 제공됩니다. 클라이언트는 모양 클래스와만 상호 작용하면 되며 하위 시스템의 여러 클래스와 직접 상호 작용할 필요가 없으므로 클라이언트의 호출 작업이 단순화됩니다.

// 子系统类
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");
    }
}

브리지 모드

기능: 추상적인 부분과 구현 부분을 분리하여 독립적으로 변경할 수 있습니다.
원리: 추상 부분과 구현 부분을 분리하는 브리지 인터페이스를 만듭니다. 추상 부분은 브리지 인터페이스를 통해 구현 부분을 호출하므로 추상화와 구현의 분리가 이루어지며 독립적으로 확장 및 변경이 가능합니다.

// 抽象部分
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();
    }
}

조합 모드

기능: 조합 모드를 사용하면 클라이언트가 단일 개체와 결합된 개체를 균일하게 처리할 수 있으므로 사용자는 단일 개체와 결합된 개체를 일관되게 사용할 수 있으므로 개체 트리 구조 사용의 복잡성이 줄어듭니다.
원리: 구성 요소 + 리프 구성 요소 + 컨테이너 구성 요소

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

// 组件接口
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();
    }
}

플라이웨이트 모드

기능: 객체를 공유하여 시스템 성능을 향상시키고 메모리 소비를 줄입니다.
원리: 객체를 공유 가능한 부분(내부 상태)과 공유할 수 없는 부분(외부 상태)으로 나누고, 내부 상태를 공유함으로써 객체 생성 및 저장을 줄입니다.

// 抽象享元接口
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)
    }
}

기타 디자인 패턴 및 해당 코드

창조적인 디자인 패턴

Supongo que te gusta

Origin blog.csdn.net/cleverstronge/article/details/131871217
Recomendado
Clasificación