Table of Contents
Preface
Facade Mode
Decorator Pattern
Home Java javaTutorial Introduction to Appearance Pattern and Decorator Pattern in Java Design Patterns (Code Example)

Introduction to Appearance Pattern and Decorator Pattern in Java Design Patterns (Code Example)

Sep 12, 2018 pm 04:06 PM
appearance mode Decorator pattern

This article brings you an introduction to the appearance mode and decorator mode in Java design patterns (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Preface

In Previous article we learned about the adapter mode and bridge mode of the structural mode. In this article, we will learn about the appearance mode and decorator mode of structural mode.

Facade Mode

Introduction

Facade mode hides the complexity of the system and provides the client with an interface through which the client can access the system. This type of design pattern is a structural pattern that adds an interface to an existing system to hide the complexity of the system.

To put it simply, it provides a simple interface to the outside world and hides the implementation logic. For example, with the power button of a commonly used computer, we only need to press the power button to start or shut down it. There is no need to know how it starts (starting the CPU, starting the memory, starting the hard disk) or how to shut it down (turning off the hard disk, turning off the memory, Turn off the CPU);

Here we can still use the example of playing games on a computer to Appearance mode for a simple explanation.
There are some online games on the computer, including DNF, LOL and WOW. We only need to double-click the icon on the computer to start and play the game. We do not need to care about how the game starts and runs.

The steps that need to be implemented are as follows:

  1. Establish the interface of the game;

  2. Establish the classes of LOL, DNF and WOW and Implement the game interface;

  3. Define an appearance class and provide it to the client for calling.

  4. Call the appearance class.

Code example:

interface Game{
    void play();
}

class DNF implements Game{

    @Override
    public void play() {
        System.out.println("正在玩DNF...");
    }
}

class LOL implements Game{
    @Override
    public void play() {
        System.out.println("正在玩LOL...");
    }
}

class WOW implements Game{
    @Override
    public void play() {
        System.out.println("正在玩WOW...");
    }
}

class Computer{
    
    private Game dnf;
    private Game lol;
    private Game wow;
    
    public Computer() {
        dnf=new DNF();
        lol=new LOL();
        wow=new WOW();
    }
    
    public void playDNF(){
        dnf.play();
    }
    
    public void playLOL(){
        lol.play();
    }
    
    public void playWOW(){
        wow.play();
    }   
}

public static void main(String[] args) {
        Computer computer=new Computer();
        computer.playDNF();
        computer.playLOL();
        computer.playWOW();
    }
Copy after login

Running result:

    正在玩DNF...
    正在玩LOL...
    正在玩WOW...
Copy after login

In the above code example, When we want to play a game, we only need to instantiate Appearance Class and call the game method in it. We don't need to care about how the game starts and runs. Moreover, each game is independent of each other and does not affect each other. Just because one game cannot be played, other games will not be able to run either. In fact, I feel that the appearance mode is very similar to the interface we usually use. They all provide interfaces to the outside world, and there is no need to care about how they are implemented.

Advantages of appearance mode:

Reduces coupling, which in some ways also improves security.

Disadvantages of appearance mode:

Does not comply with the opening and closing principle and is not easy to change.

Usage scenarios

When there are multiple complex modules or subsystems in the system.

Decorator Pattern

Introduction

The Decorator pattern allows adding new functionality to an existing object without changing its structure. This type of design pattern is a structural pattern, which acts as a wrapper around an existing class.

The decorator mode, as the name suggests, is to decorate something so that it can provide some additional functions. For example, decorating people and wearing different costumes when doing different things. For example, putting on a jersey means getting ready to play ball, putting on a swimsuit means getting ready to go swimming, etc.

The decorator pattern can dynamically add some additional responsibilities to an object.

Here we still use an example to illustrate.
Among the current toy models, there are two very popular models, GUNDAM model and MrGu model. When we are piecing together the models, Generally, the model is assembled first, and then some additional accessories, such as weapons, are added. Here we have assembled the GUNDAM model and the MrGu model and then equipped them with their respective weapons.

The specific implementation steps are as follows:

  1. Create a model interface of abstract components, with the assembly method;

  2. Create Specific component classes (GUNDAM class and MrGu class), and implement the above model interface;

  3. Define a decorator to accept the client's request and respond according to the client's request Call;

  4. Define a class that specifically implements decoration, which is used to add corresponding functions to the object.

Code example:

interface Model{
    void  assemble();
}

class GUNDAM implements Model{
    @Override
    public void  assemble() {
        System.out.println("组装一个高达模型");
    }
}

class MrGu implements Model{
    @Override
    public void  assemble() {
        System.out.println("组装一个扎古模型");
    }
}

abstract class  AddExtra implements Model{
    protected  Model model;
    
    public AddExtra(Model model){
        this.model=model;
    }
    public  void assemble(){
        model.assemble();
    }
}

class LightSaber extends AddExtra{

    public LightSaber(Model model) {
        super(model);
    }
    
    public  void assemble(){
        model.assemble();
        addLightSaber();
    }
    public void addLightSaber(){
        System.out.println("添加光剑");
    }
}


class RocketLauncher extends AddExtra{

    public RocketLauncher(Model model) {
        super(model);
    }
    
    public  void assemble(){
        model.assemble();
        addRocketLauncher();
    }
    public void addRocketLauncher(){
        System.out.println("添加火箭筒");
    }
}

public static void main(String[] args) {
    
        Model gundam=new GUNDAM();
        Model mrgu=new MrGu();
        gundam.assemble();
        mrgu.assemble();
            
        Model gModel=new LightSaber(new GUNDAM());
        gModel.assemble();
        Model mModel=new RocketLauncher(new MrGu());
        mModel.assemble();
}
Copy after login

Running result:

    组装一个高达模型
    组装一个扎古模型
    
    组装一个高达模型
    添加光剑
    组装一个扎古模型
    添加火箭筒
Copy after login

In the above code, if we only want to assemble Gundam Or this Zaku model, you can directly instantiate the model class and call the methods in it. If you need to add a weapon when assembling the model, you only need to add the corresponding function through the decorator class.
Through this example, we found that when trying to use the decorator mode, some classes can be extended without affecting the previous functions, improving flexibility.

Advantages of the decorator pattern:

The decorating class and the decorated class can develop independently, with low coupling, easy expansion, flexibility and convenience.

Disadvantages of the decorator pattern:

Decorating a class too much will increase complexity.

Usage scenarios
When the prototype remains unchanged and some functions are dynamically added.

Related recommendations:

Introduction to adapter pattern and bridge pattern in Java design patterns (code examples)

Introduction to builder pattern and prototype pattern in Java design patterns Introduction (Code Example)

The above is the detailed content of Introduction to Appearance Pattern and Decorator Pattern in Java Design Patterns (Code Example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles