Analysis of Objective-C design pattern appearance

Time:2021-4-26

The pattern of picture recognition

Self help tour (Figure 1)

Analysis of Objective-C design pattern appearance

Travel Agency (Figure 2)

Analysis of Objective-C design pattern appearance

A chestnut, for example

I don’t know if you have any travel experience through travel agencies? This is a good application of appearance pattern.

Mode 1: customers directly call the functions of each subsystem to form a tight coupling relationship with each subsystem (Figure 1)
Mode 2: provide a high-level interface, which is responsible for interacting with subsystems and providing customers with the interfaces they need to use (Figure 2)
As can be seen from the schematic structure of the above two modes, mode 2 is much better than mode 1 for customers, because in mode 2, customers do not need to know the logic of each subsystem, they only need to interact with the high-level interface. In fact, mode 2 is the appearance mode we are going to talk about here.

If the appearance mode is not applied here, we (the client in the picture above) will have to contact transportation, book hotel, restaurant, scenic spot tickets and so on. I believe this kind of journey will make you feel very tired. With the appearance character (facade in the picture above), it will help us deal with these things.

Dimiter’s law

brief introduction

Law of Demeter (LOD), also known as “principle of least knowledge”, is a guiding principle for software development, especially for object-oriented programming. Demeter’s law is a concrete case of loose coupling. This principle was invented by Northeastern University at the end of 1987.
The name of this principle comes from the Greek goddess of agriculture, the lonely Demeter.

definition:One object should have minimal knowledge of other objects.
The origin of the problem is as followsThe closer the relationship between classes, the greater the degree of coupling. When one class changes, the greater the impact on another class.

Solution:Minimize the coupling between classes.

Since we came into contact with programming, we have known the general principles of software programming: low coupling, high cohesion. Whether it is process oriented programming or object-oriented programming, only make the coupling between each module as low as possible, can improve the reuse rate of code. The advantage of low coupling is self-evident, but how to program to achieve low coupling? That’s what the Demeter’s law does.
Dimiter’s rule, also known as the least known principle, was first proposed by Ian Holland of Northern University in 1987. Generally speaking, the less a class knows about its dependent classes, the better. That is to say, no matter how complex the logic is, the dependent class will try its best to encapsulate the logic inside the class, and will not disclose any information except the public method. There is a simpler definition of Dimiter’s Law: to communicate only with direct friends. First of all, let’s explain what a direct friend is: each object has a coupling relationship with other objects. As long as there is a coupling relationship between two objects, we say that the two objects are friends. There are many ways of coupling, such as dependence, association, combination, aggregation, etc. Among them, we call the classes that appear in member variables, method parameters and method return values as direct friends, while the classes that appear in local variables are not direct friends. That is to say, it’s better not to appear inside the class as a local variable.

Some metaphors

The most common metaphor is: don’t talk to strangers

Look at this: suppose I shop in a convenience store. When I pay, should I give my wallet to the cashier and ask her to open it and take out the money? Or do I just hand her the money?

Let’s make another analogy: people can command a dog to walk, but they should not direct the dog’s legs to walk, instead, the dog should direct and control how the dog’s legs walk.

Mode and significance

Dimiter’s rule can be simply said: talk only to your immediate friends. For ood, it is interpreted as the following ways: a software entity should interact with other entities as little as possible. Each software unit has the least knowledge of other units, and is limited to those closely related to its own unit.
The original intention of Dimiter’s law is to reduce the coupling between classes. Because each class is less dependent on other classes, it is easy to make the functional modules of the system function independent, and there is no (or little) dependency relationship between them.
Demeter’s law doesn’t want to establish a direct connection between classes. If you really need to establish a connection, you also want to convey it through its friend class. Therefore, the application of dimitt’s rule may result in a consequence: there are a large number of intermediary classes in the system, and the reason why these classes exist is to transfer the calling relationship between classes, which increases the complexity of the system to a certain extent.
Facade and mediator are examples of the application of Dimiter’s law.
It is worth mentioning that although Ian Holland’s contribution to computer science is limited to this rule, and his achievements in other areas are few, this rule is not only limited to the computer field, but also applicable in other fields. For example, Americans use this rule in the design of space systems.

Schema definition

Appearance mode provides a unified interface for a group of different interfaces in a subsystem. Appearance defines the upper interface, which makes the subsystem easy to use by reducing the complexity and hiding the communication and dependency between subsystems.

Users of the API have no idea how complex the internal business logic is. When we have a large number of classes and they are complex to use and difficult to understand, appearance patterns are an ideal choice.
Appearance pattern successfully decouples the use and implementation logic behind, and reduces the dependence of external code on internal work. If the underlying class changes, the appearance of the interface does not need to be changed.

Structure chart

Analysis of Objective-C design pattern appearance

This definition should be well understood through the illustration in the introduction above. Here we will analyze two important roles in the definition:

Appearance role: it is the “high level interface” in the introduction diagram. The client can call the method of this role; In addition, the role knows the functions and responsibilities of the relevant subsystems.

Subsystem role: can have one or more subsystems at the same time. Each subsystem can be called directly by the client or by the appearance role.

code

For example, today I didn’t want to drive, so I called for a taxi. As long as the taxi can get me to my destination, I don’t care about the license plate and model. I would say “I’m going to someplace” directly to the driver, and then the driver would perform a series of actionscommand(release the handbrake, shift, step on the accelerator, etc.). The taxi driver abstracts the details of the bottom layer responsible for driving the car. He separated me from the original complex vehicle operation interface by providing driving service (simplified interface). The direct interface between taxi and me is just a simple “I’m going to XXX”.

In many old object-oriented applications, there may be many classes scattered in the system with various functions. To use these classes for a function, you need to know all the details to use them in a set of algorithms. If you logically combine some of these classes into a simple interface, you can make them easier to use.

Analysis of Objective-C design pattern appearance

Write the code

Car defines several methods to manipulate its internal objects, such as pressbrakes, releasebrakes, changgears. If the client wants to use the internal functions of car, it must know how to use these methods to operate correctly.

@interface Car : NSObject

///Step on the brake
- (void)pressBrakes;
///Release the brake
- (void)releaseBrakes;
///Shifting
- (void)changGears;
///Step on the gas
- (void)pressAccelerator;
///Release the throttle
- (void)releaseAccelerator;

@end 


@implementation Car

- (void)pressBrakes
{
    Nslog (@ "car: brake");
}

- (void)releaseBrakes
{
    Nslog (@ "car: release brake");
}

- (void)changGears
{
    Nslog (@ "car: shift");
}

- (void)pressAccelerator
{
    Nslog (@ "car: step on the accelerator");
}

- (void)releaseAccelerator
{
    Nslog (@ "car: release the throttle");
}

@end

Taximeter itself is a complex system. It has two methods for clients to manipulate its objects. The start and stop methods just let Taximeter start or stop. We don’t go into the details of Taximeter here.

@interface Taximeter : NSObject

///Start typing
- (void)start;
///Finish typing
- (void)stop;

@end  


@implementation Taximeter

- (void)start
{
    Nslog (@ "Taximeter: start table printing");
}

- (void)stop
{
    Nslog (@ "Taximeter: end tabulation");
}

@end

At present, there are two complex subsystems in taxi service system. A cardriver is required as theappearanceTo simplify the interface. The code is as follows

@interface CarDriver : NSObject

- (void)driveToLocation:(CGPoint)place;

@end  


@implementation CarDriver

- (void)driveToLocation:(CGPoint)place
{
    // ....
    
    //Turn on the meter
    Taximeter *meter = [Taximeter new];
    [meter start];
    
    //Operate the vehicle until position place is reached
    Car *car = [Car new];
    [car releaseBrakes];
    [car changGears];
    [car pressAccelerator];
    
    // ....
    
    //Place, stop and meter
    [car releaseAccelerator];
    [car pressBrakes];
    [meter stop];
    
    // ....
}

@end

The appearance method of cardriver determines how easy the client can use the whole taxi service system. The customer only needs to call the drivetolocation: method, and the rest of the operation will take place in the message call. The client doesn’t need to know what’s going on at the bottom.

summary

Through the above explanation, let’s analyze the characteristics of appearance mode

  • Facade design pattern focuses on the whole system from the architecture level, rather than the level of a single class. Most of the time, it is an architecture design pattern, such as our common three-tier architecture.

  • Facade mode simplifies the interface of the whole system, at the same time, it also achieves a “decoupling” effect for the internal system (subsystem) and external program (client).

According to the characteristics of appearance mode, we can use facade mode in the following situations:

  • If you don’t need to use all the functions of a complex system and only need to use part of the functions of the system, you can apply FA ç The ade mode provides a high-level interface, which is much simpler than calling the interface of the original system directly.

  • When you want to encapsulate or hide the interface of the original system, you can consider using appearance mode.

  • Hope to use part of the original system functions, but also hope to add some new functions.

  • When building a hierarchical subsystem, facade pattern is used to define the high-level interface of each layer in the subsystem. If the subsystems are interdependent, you can make them communicate only through the facade, thus simplifying the dependency relationship between them.

In fact, this design pattern is very common. We usually have this pattern when we use third-party classes. When we use third-party classes, we only need to refer to one of the third-party files to change it to meet the needs of many functions. I just want to add some methods of subsystem to this file, so that users can get started faster.

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]