Java Design Patterns - Appearance Pattern
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:
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; } }
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); } }
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:
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); } }
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); } }
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; } }
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
