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

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

Running result:

    正在玩DNF...
    正在玩LOL...
    正在玩WOW...

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

Running result:

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

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
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
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 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 use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

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 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...

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...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor