Learn design patterns one by one, and when you understand them, crumb them up, break them up, and then modify existing projects and think about which design patterns you can use.
The path to design patterns
- Familiarity stage, as if every design pattern is consistent with the current situation, different design patterns have ambiguity, similarities, and violations of design principles, seem to be able to solve. Don’t be afraid to pick the one that feels best for you.
- Use stage, will be a variety of design mode mixed use, the whole clearly, but the design will be a little stiff, lack of flexibility
- The design pattern is rotten and in my heart. When writing code, I naturally use my own pattern for a long time. According to the seven principles of design pattern, I write excellent code
- Magically, the design principles are already in your subconscious mind, and you are already experimenting with new principles.
Just like When Zhang Wuji learned tai chi with Zhang Sanfeng, all the learning is the entrance; Forget it all, and then you’re in a good place. It’s still a long way from being a god.
List of design pattern principles
- The open and closed principle is the general principle. It tells us to be open to expansion and closed to modification.
- Richter’s substitution tells us not to break the inheritance system;
- The dependency inversion principle tells us to program for interfaces;
- The single responsibility principle tells us to implement a class with a single responsibility;
- The principle of interface isolation tells us to keep interfaces simple and simple when designing them.
- Demeter’s rule tells us to reduce coupling;
- The principle of composite reuse tells us to use composite or aggregate relation reuse in preference to inheritance relation reuse.
schedule
The name of the | classification | thought | role | The sample |
---|---|---|---|---|
Simple Factory model | Create a type | Use a factory to create the same kind of thing required | Concrete factory class, Abstract object class, concrete object class | Factory produces round, square, oval and diamond buttons |
Factory method pattern | Create a type | Use one factory to create the same kind of thing with multiple requirements | Concrete factory class, Abstract object class, concrete object class | The Factory produces round, square, oval, and diamond buttons, and differentiates between dark theme and normal mode |
Abstract Factory pattern | Create a type | Use a factory to create different kinds of things with multiple requirements | Abstract factory, factory, abstract product variety, concrete product variety | Factory produces round, square, oval, diamond controls, while distinguishing between dark theme, or normal mode; Controls include buttons, UILabel, UIView, UIImageView |
Builder model | Create a type | Create a complex thing | The commander, the abstract builder, the concrete builder, the built object | Learn builder mode by ordering in KFC |
The singleton pattern | Create a type | Single, repeated, frequent use | x | XXManager,XXServer,UserDefault |
= | = | = | = | = |
Adapter mode | structured | Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee Adaptee | Adaptee, Adapter, Target | Learn adapter patterns by scrolling through a diagram |
The bridge model | structured | When A wants to use B but cannot do so through inheritance and combination | Bridge files, which should be extremely complicated black boxes | Apple provides the idea of using Bridges, one is native OC, Swift calls JS, another is Swift calls OC; One example I can think of: We use Swift to parse Lottie’s JSON file ourselves, and then modify the values inside to animate, change width, height, and color |
Decorator mode | structured | Add methods to objects dynamically | x | Protocol oriented programming in SWIFT and Extension share this idea |
The appearance model | structured | Reduce interaction between different classes and provide a unified interface | User, appearance, sub-function | In fetching a resource class, you need to call the local cache and network data respectively, and finally return the combined result. Implementing isolation reduces interaction between classes |
The proxy pattern | structured | Occupy pit first, asynchronous operation | x | Time-consuming operation, images load asynchronously |
The flyweight pattern | structured | Caching systems that cache in memory and reuse a lot are good for things with less granularity | x | x |
= | = | = | = | = |
Command mode (×) | Behavior type | Abstract commands into objects, concrete command objects that provide interfaces to the outside world and are responsible for the execution of commands | Abstract command class, concrete command class, caller, receiver | Design Mode Series 6– Command mode |
The mediator pattern | Behavior type | By encapsulating a set of object interactions with a mediation object, the mediator loosens the coupling of objects without explicitly referring to each other, and can change their interactions independently | Mediator: ConcreteMediator, Colleague: ConcreteColleague | Design Patterns Series 3– Mediator patterns |
Observer model | Behavior type | Active observation of state changes, resulting in changes, one-to-many scenarios | Abstract target, target, abstract observer, observer | KVO, Notification, |
The state pattern | Behavior type | The behavior of an object depends on its State. An environment class is actually an object that owns State. An environment class can sometimes act as a State Manager in which you can switch states | Environment class, Abstract state class, concrete state class | Design Patterns Series 9– State patterns. |
The strategy pattern | Behavior type | Define a set of algorithms, encapsulate them one by one, and make them interchangeable. The policy pattern allows the algorithm to change independently of the clients that use it | Environment class, Abstract policy class, concrete policy class | X module has A piecewise function, X module is required for A, B, C, but have different requirements of piecewise function in X module, at this time, you can write the if and else statements in X module, or A switch statement, but this violation of the principle of opening and closing, so the better way is to put the function algorithm is used to encapsulate, passed as A parameter to enter. |
Creation pattern
-
The creative pattern gives the software designer as much flexibility as possible in What to create, Who to create, and When to create.
-
The creation pattern hides the creation details of instances of classes, making the whole system independent by hiding how objects are created and grouped together.
-
Description: The mode to use when creating objects
-
Keywords: Build, build, construct, create, factory mode
1. Simple factory model
- Scenario: Producing a single type of product
- Roles: factory, abstract product, concrete product
- See Factory Mode three Brothers
Ii. Factory design mode
- Scenario: Production of a single type of product (large quantity, distributed to different factories)
- Roles: Abstract factory, factory, abstract product, concrete product
- See Factory Mode three Brothers
Abstract factory model
- Scenario: Production of multiple types of products (in large quantities, distributed to different factories)
- Role: Abstract factory, factory, abstract product variety, concrete product variety
- See Factory Mode three Brothers
Fourth, the builder model
- Learn builder mode by ordering in KFC
5. Singleton mode
- Scenario: single, repeated, frequent use
- Note: Some resources are released when they are no longer needed, or when a memory warning is received
- Example: XXManager XXServer, UserDefault
Structural mode
- Description: when a function is more complex, how can it be reused and combined to form a complex and more powerful structure
- Keywords: frame, decoupling, isolation, composition, structure
- Structural patterns can be divided into class structural patterns and object structural patterns
- The class-structured pattern is concerned with the composition of classes, from which multiple classes can be combined into a larger one
- The object structural pattern is concerned with the composition of classes and objects by associating them so that an instance object of another class is defined in one class and its methods are called through that object. According to the principle of composite reuse, relational relationships are used instead of inheritance relationships in the system, so most structural patterns are object structural patterns.
Adapter mode
- Adaptation, reference UITableViewdelegate, UITableViewDataSource
- Example: Learn adapter patterns by scrolling through a diagram
Second, bridge mode
- When A wants to use B but cannot do so through inheritance and combination
- Bridge files, which should be extremely complicated black boxes
- Apple provides the idea of using Bridges, one is native OC, Swift calls JS, another is Swift calls OC;
- One example I can think of: We use Swift to parse Lottie’s JSON file ourselves, and then modify the values inside to animate, change width, height, and color
Decorator mode
- Dynamic extension methods, functions
- Example: Protocol oriented programming in Swift and Extension share this idea
4. Appearance mode
-
Description: Reduce the interaction between different classes, provide a unified interface
-
Example: For example, in obtaining resource classes, local cache and network data need to be called to achieve isolation and reduce interaction between different classes
-
Code: https://www.raywenderlich.com/477-design-patterns-on-ios-using-swift-part-1-2#toc-anchor-007
5. Agency mode
- Description: Occupy pit first, after operation
- Example: Time-consuming operation, image load asynchronously
Six, enjoy yuan mode
- Cache system, cache in memory, a lot of repeated use for smaller particles
- Example: Unknown
Behavioral pattern
-
Note: By communicating and collaborating with each other to perform some complex functions, one object at run time will also affect the operation of other objects
-
Keywords: observation, notification, MVC, feedback, monitoring
-
Behavioral pattern can be divided into class behavior pattern and object behavior pattern:
- Class behavior pattern: The behavior pattern of a class uses inheritance relationships to distribute behavior among several classes. Class behavior pattern mainly distributes responsibilities of parent and subclass by means of polymorphism.
- Object behavior pattern: The object behavior pattern uses the aggregate association of objects to assign behaviors. The object behavior pattern mainly assigns responsibilities of two or more classes through object association. According to the principle of composite reuse, association relation should be used to replace inheritance relation, so most behavior design pattern belongs to object behavior design pattern.
First, command mode
- Abstract the command into an object, the specific command object, to provide interface to the outside world, while responsible for the execution of the command
- Example: Design Mode Series 6– Command mode
Second, the intermediary model
- Note: A and B do not communicate with each other, but communicate through C.
- Example: For example, the Model and View in MVC do not communicate directly, but communicate through Controller; In real life, intermediary companies do just this job, and controllers deal with too many things, which will become more and more complicated and bloated. The disadvantages of this mode are also the same.
- Design Patterns Series 3– Mediator patterns
Observer model
- Description: Active observation of state change, thus change
- Examples are KVO and Notification
4. State mode
- Description: Allows an object to change its behavior when its internal state changes. Object appears to have modified its class.
- Example: Design Patterns Series 9– State patterns
- Personal understanding: If in different states, there may be the same operation, then the state is encapsulated into a class, the operation is defined as a protocol, each state class comply with this protocol, and implementation.
5. Strategic mode
- Description: define a series of algorithms, encapsulate them one by one, and make them interchangeable. The policy pattern allows the algorithm to change independently of the clients that use it.
- Example 1: Design Patterns Series 8– Policy patterns
- Example 2: X module has A piecewise function, X module is required for A, B, C, but have different requirements of piecewise function in X module, at this time, you can write the if and else statements in X module, or A switch statement, but this violation of the principle of opening and closing, so the better way is to put the function algorithm is used to encapsulate, passed as A parameter to enter.
Reference links:
- https://juejin.cn/post/6844903934230806535
- https://design-patterns.readthedocs.io/zh_CN/latest/index.html
- https://juejin.cn/user/3526889030556574
This article is formatted using MDNICE