Home Java javaTutorial Java Design Patterns - Appearance Pattern

Java Design Patterns - Appearance Pattern

Feb 06, 2017 am 11:44 AM

Overview

The appearance pattern I’m going to talk about today is a relatively simple design pattern, and in daily development, you may also use it from time to time, but you may not have thought that it is a design. model. This article will start with some examples to explain the appearance mode to be explained in this article as comprehensively as possible. Hope it is beneficial to you.

Introduction

The purpose of inserting a quotation here is to let you recall when you use the appearance pattern in your daily development.

Maybe your boss will arrange a task for you like this. This may be a core module, and the module will have one of its functions, but your boss may only want you to provide an interface for him to call. He will tell you this: Hi, Xiao Ming, our current system needs a core function P0, let you implement it. You just need to give me an interface that I can call. I don't need to know the internal logic of your code. go a head.

If you are often assigned such tasks, I think you should have mastered the appearance mode.

Definition

The appearance pattern provides a unified interface for accessing a group of interfaces in the subsystem. The facade pattern defines a high-level interface that makes subsystems easier to use.

Non-appearance mode

Here I will use the example in the book "Dahua Design Pattern". I feel that this example is quite vivid. Now imagine that you are a stock investor (it’s just that the blogger doesn’t trade in stocks, and I don’t know if there is something wrong here. If so, just pretend you didn’t see it. ^_^), and you want to do some financial management activities. You are interested in two stocks, one Treasury bond and one real estate.

If you are asked to write this code now, your code framework may look like the following class diagram:

Java Design Patterns - Appearance Pattern

Only stocks are listed here code because the logic of other financial management activities is consistent with the logic of stocks. Redundant code has no more benefits than taking up space.

StockA.java

public class StockA {
    private int stockCount = 0;
    public void sell(int count){
        stockCount -= count;
        System.out.println("卖了" + count + "支 A 股票");
    }

    public void buy(int count){
        stockCount += count;
        System.out.println("买了" + count + "支 A 股票");
    }
    public int getStockCount() {
        return stockCount;
    }
}
Copy after login

The following code is for financial managers. For a simple buying and selling logic, financial managers have to spend so much code processing, which is really torturous. Well.

Investors.java

public class Investors {

    public static void main(String[] args) {
        StockA stockA = new StockA();
        StockB stockB = new StockB();
        NationalDebt debt = new NationalDebt();
        RealEstate estate = new RealEstate();

        stockA.buy(100);
        stockB.buy(200);
        debt.buy(150);
        estate.buy(120);

        stockA.sell(100);
        stockB.sell(200);
        debt.sell(150);
        estate.sell(120);
    }
}
Copy after login

The above mentioned are codes written without using appearance mode. In other words, the appearance mode mentioned below can make the code simpler and clearer.

Appearance mode

In the above non-appearance mode, we see some code logic that is not very friendly. The appearance mode can be based on a higher level of encapsulation to be more transparent to the caller. The following is the modified appearance mode class diagram:

Java Design Patterns - Appearance Pattern

FundFacade.java

public class FundFacade {

    private StockA stockA = null;
    private StockB stockB = null;
    private NationalDebt debt = null;
    private RealEstate estate = null;

    public FundFacade() {
        stockA = new StockA();
        stockB = new StockB();
        debt = new NationalDebt();
        estate = new RealEstate();
    }

    public void buyAll(int count) {
        stockA.buy(count);
        stockB.buy(count);
        debt.buy(count);
        estate.buy(count);
    }

    public void sellAll(int count) {
        stockA.sell(count);
        stockB.sell(count);
        debt.sell(count);
        estate.sell(count);
    }

    public void buyStockA(int count) {
        stockA.buy(count);
    }

    public void sellNationalDebt(int count) {
        debt.sell(count);
    }
}
Copy after login

The above code is the core class of appearance: FundFacade. All operations in the financial management system can be implemented through this class. Through this class, you can easily operate financial management projects such as stocks, treasury bonds, and real estate without worrying about how they are processed. That's a good thing for users, isn't it?

Let’s take a look at the user’s operations (of course the above diagram class has reflected most of the effects), this is the user’s code logic:

Investors.java

public class Investors {

    public static void main(String[] args) {
        FundFacade facade = new FundFacade();
        facade.buyAll(120);
        facade.buyStockA(50);
        facade.sellAll(80);
    }
}
Copy after login

Look, the user only needs to tell the FundFacade class what to buy, what to sell, how much to buy, and how much to sell, and the purpose can be achieved. It's so convenient.

Look at the code of stock A. In fact, it has no substantial changes. This is also the charm of the appearance mode. It does not require you to modify the code of the original subsystem. You only need to do one thing and build a higher-level encapsulation. Of course, I made some simple changes here to access the StockA. Since it needs to be transparent to users, there is no need for my subsystem to be open to users anymore, right? Because we already have professional diplomats - FundFacade.

StockA.java

class StockA {
    private int stockCount = 0;
    void sell(int count){
        stockCount -= count;
        System.out.println("卖了" + count + "支 A 股票");
    }

    void buy(int count){
        stockCount += count;
        System.out.println("买了" + count + "支 A 股票");
    }
    int getStockCount() {
        return stockCount;
    }
}
Copy after login

The appearance pattern is a relatively simple design pattern that you can easily master and use. I just want to say that the appearance mode also has certain limitations. I believe you have discovered it.

Since we hand over all operations to the subsystem to the FundFacade class, we are constrained by the FundFacade class. For example, the FundFacade class above does not implement separate operations on StockB, so we cannot operate on StockB alone unless you encapsulate an interface for operating StockB in the FundFacade class.

Application of appearance mode

In the above description, we not only know how to use appearance mode, but also understand the limitations of appearance mode, so we should take an objective stance and be selective use it. Here is an example of how I use appearance mode in my work.

The boss of the current project asked me to implement a certain module in a system. I think this should be a core module. The function of this module is to check whether all files in a folder contain sensitive information. There will be many small sub-modules in this module (of course the boss will not care about what these sub-modules do), such as pattern matching of AC automata, fully automatic decompression of compressed files, various format files (doc/xls/ ppt/zip/eml/rtf/pdf, etc., most of the file formats are basically there), log system, etc.

It is impossible for me to tell the boss that the function you want to complete is what to do first, what to do next, what to do next, what to do next...

Oh, Gosh. It's so annoying, can you encapsulate it? (Of course, these are just my psychological activities. In fact, I have not asked the boss to explain my design process)

After encapsulation, I only need to tell the boss to call this method of this class and it will be ok. In this way, the boss doesn't have to worry about the logic inside. Although it is your responsibility if something goes wrong, it should be your responsibility. Ha ha. . .

Okay, that’s it for the bullshit. Whether it is the detailed explanation of the serious pattern above or the nonsense below, I hope it can allow you to fully understand the design pattern in this article, learn and use it rationally.

The above is the content of Java design pattern - appearance pattern. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles