The resources
-
Head First Design Mode (Chinese Version) — Freeman (E)
-
Big Talk design Patterns by Cheng Jie
Reprint note: Nuggets exclusive release, prohibit reprint. — hlwang
Review:
This article summarizes the design patterns in architectural design in recent years.
In my opinion, the design pattern technique describes a world of “impersonal” : “Objects should not meet face-to-face, each should do his or her own job, and it is better not to know the existence of a particular object”.
- Strategy pattern: Algorithm family
- Observer pattern: Extremely decoupled, a classic case of the open and closed principle.
- Decorator pattern: Russian nesting dolls, one of the classic cases of the open and close principle, imagine if the decorator object is used by thousands of businesses, you a new business dare to modify its line of code?
- Factory pattern: Abstract-oriented programming, relies on inversion
- Command mode: Send express. You are the initiator of the order (send express), the Courier receiver is the receiver of the order, logistics freight specific implementation of transport. In this scenario, do you need to care about the delivery guy? Don’t need. Delivery guy, do you need to care whether the delivery is delivered by truck or by plane? Obviously not. Does logistics need to care about senders? I don’t need it. Imagine if three parties care about each other. Is there room for iteration in your program?
- Adapter: Sun Wukong seventy-two change makeup into goblin deep enemy hole intelligence.
- Model approach. In e-commerce business, the algorithm design for users to click the buy button is as follows: login or not –> identity verification (purchase) –> order. Identity verification may be different for different e-commerce sub-services. For example: gold coin exchange, new customer business, etc., need to verify different data parts.
- Iterator pattern: The iterator has the shadow of the adapter, and the adapter has the shadow of the agent, so go ahead.
- Combination mode: Song of whole and parts
- State mode: classic case – seconds kill business scenario: reservation available -> countdown -> Snap up -> Sold out -> Finished, each node can use a node to encapsulate.
I. Strategic mode
Definition:
Families of algorithms are defined so that they are interchangeable, and this pattern makes changes to the algorithm independent of the customers using it.
Sc:
- Both the strategy pattern and the model approach are algorithmic, but the former uses composition and the latter relies on inheritance.
- Encapsulate changes. Algorithm-oriented programming, then the strategy pattern solves a “point” problem. The algorithm is large, comprehensive and all-encompassing, so it is easy to be coupled, and when changing, it is not easy to cut accurately.
- Interface/supertype oriented programming, not dependency oriented
Application Scenarios:
The most widely used design pattern.
- RecyclerAdapter(adapter mode) and RecyclerView(adapter customer) are different strategies.
- Volley, Google’s lightweight web library, makes heavy use of the policy model
- In theory there is
if/else
You can use the policy pattern.
Observer model
define
Defines a one-to-many dependency between objects. When an object’s state changes, dependent objects are notified and updated automatically.
sc
- There are some differences to distinguish it from the publish-subscribe model
- Solutions of the coupling. Let me know if the state changes. What happens? It’s my business
- Pay attention to
register
withunRegister
Pair, watch out for memory leaks. So, one more question,“Must strong coupling be used for the observer pool in the subject?”
Application scenarios
- RxJava. A cascading observer of matryoshka dolls. They’re really good.
- Custor ContentProvider + + CustorAdapter. Cascade observer, case can refer to: Android source code – SHORT MMS – SMS list data implementation.
Three, decorator mode
define
By adding responsibilities to objects dynamically, decorators offer a more flexible solution to extending class functionality than inheritance.
sc
- Russian nesting dolls. Combinatorial way of holding decorative object handles. An additional point to note here is that there is no inheritance among decorators, but decorators do not obtain “behavior” through inheritance, but to obtain the same type.
- Class to explode. Inheritance results in a “class explosion”. The decorator pattern focuses on the last sentence: elasticity.
- Again, use composition to solve problems, note and strategy pattern differentiation.
- Open – close principle. This may seem confusing to beginners and may sound contradictory, but think about decorators, which extend the behavior of the original object without changing a single line of the original object’s code. Imagine if a decorator object is used by thousands of businesses. Would a new business dare to change a single line of its code?
Application scenarios
- A classic case: InputStream + BufferedInputStream/LineInputStream, IO all understand.
- Now that we’re talking about Matryoshka dolls, RxJava is a classic example. Each Operator in RxJava is its application, dynamically assigning responsibility to the new object. RxJava website
- View + ViewGroup + LinearLayout.
Four, factory
define
Simple factories: not so much design patterns as programming habits, conventions. Factory methods: Define methods for creating objects, but it is up to subclasses to decide which objects to instantiate. This pattern delays the creation of objects to subclasses. Abstract Factory: Defines an interface for creating families of object dependencies or dependencies without specifying concrete classes.
sc
- The object creator pattern is very widely used.
- For abstract programming. The factory method, for example, defines the way to create an object, that is, we define an object abstraction and the object to create must be a subtype of it. For customers using this pattern, it doesn’t care about specific object types at all.
- Dependency inversion/dependency inversion. You can’t have a higher-level component depend on a lower-level component; both should depend on abstraction.
Application scenarios
- Adapter (RecyclerViewAdapter). The Adapter defines a family of object dependencies, such as count(), viewType(), ViewHolder(), getId(), and so on. Imagine how convenient it would be to change the list display and simply replace it with a new Adapter.
- Android source code Framework Telephony module. Different call protocols, such as GsmPhone and CDMAPhone, use Phone as the interface to produce related or dependent families.
5. Singleton mode
define
Ensure that a class has only one object and provides global access points.
sc
Seven ways to write a singleton pattern
6. Command mode
define
Encapsulate requests as objects so that objects can be parameterized with different requests, queues, logs, and can be applied to scenarios such as undo operations.
sc
- Command mode is a separation of roles, each of which can have its own decisions.
- Send it special delivery. You are the initiator of the order (send express), the Courier receiver is the receiver of the order, logistics freight specific implementation of transport. In this scenario, do you need to care about the delivery guy? Don’t need. Delivery guy, do you need to care whether the delivery is delivered by truck or by plane? Obviously not. Does logistics need to care about senders? I don’t need it. Imagine if three parties care about each other. Is there room for iteration in your program?
Application scenarios
- Android Handler + Msg. Handler is particularly common in Android, so I won’t elaborate.
7. Appearance mode
define
Provides a unified interface to a set of interfaces for accessing subsystems. The facade pattern defines a high-level interface that makes subsystems more accessible.
sc
- The facade pattern avoids tight coupling between the client and the subsystem.
- The least knowledge principle/Dubitt’s Law. Remember that sentence at the beginning of the article? If you know what subsystems can do for you, try not to allow the main system to be coupled to subsystems.
Application scenarios
- Initialization provided by the tripartite component
init
interface
Viii. Adapter
define
Translate the interface of a class into the desired interface of the customer. This pattern allows incompatible interface types to work together.
sc
- The converter. There is a shadow of proxy pattern in the pattern, but the emphasis of the pattern is on the interface method transformation, in order to make the program more compatible, reduce the complexity of the program. Similar: Sun Wukong seventy-two makeup into a goblin in-depth enemy cave intelligence.
Application scenarios
- The Adapter.
- Use with decorator. Decorators require the same supertype, where the adapter pattern comes in handy.
Nine, template method
define
Within a method, the skeleton of the algorithm is defined and part of the steps of the algorithm are deferred to subclasses. The template approach lets subclasses redefine certain steps in an algorithm without modifying the structure of the algorithm.
parsing
- It involves algorithms, it involves latency to subclasses. You don’t think of the policy pattern versus the factory method pattern.
- Use inheritance to solve problems.
Application scenarios
- Lifecycle approach
- RecyclerAdapter. VH onCreateViewHolder + onBindViewHolder are subclassed.
- In e-commerce business, the algorithm design for users to click the buy button is as follows: login or not –> identity verification (purchase) –> order. Identity verification rules vary with e-commerce sub-service scenarios. For example: gold coin exchange, new customer business, etc., need to verify different data parts.
Iterator pattern
define
Provides a way to access the individual element data in a collection sequentially without exposing its internal implementation.
sc
- The iterator has the shadow of the adapter, and the adapter has the shadow of the agent, so go ahead.
- First, iterators provide a way of sequential access. Key two: is not exposed to internal implementation.
Application scenarios
- Traverse the access scenario
- java.util.Iterator
11. Combination mode
define
Allow your objects to be grouped into a tree structure to represent a whole/part hierarchy so that individual objects and combinations of objects are handled in a consistent manner.
sc
- Whole/part. The whole is also made up of parts, so individual objects and combinations of objects can be handled in a consistent manner.
Application scenarios
- Company and Branch
- Main menu and submenu
Xii. State mode
define
Allows an object to change its behavior when its internal state changes, as if the object changed its class.
sc
- The state pattern is identical to the policy pattern class diagram. The main difference is intent.
- Phenomena have a timeline, and as time changes, the state changes, and the features that the class provides to the outside world change.
Application scenarios
- Second kill service. Seconds kill business scenarios: available for appointment -> countdown -> Snap up -> Snapped up -> Finished, each node can use a node to encapsulate.
- Android source code Framework – Wifi. WifiStateMachine, the realization of Wifi working scenarios: scanning, connection, connection success.
State machine framework components
13. The difference between agent mode and decorator mode?
Q: The UML for decorator and proxy patterns is basically the same. What is the difference?
The decorator pattern should provide enhancements to the objects it decorates, whereas the proxy pattern exerts control over the use of the objects it projects and does not provide enhancements to the objects themselves.
In terms of usage, the proxy mode usually determines the target object to be propped in the proxy class, and the client is not aware of the existence of the propped class. In decoration mode, the decorator object needs to be provided by client creation, and can be nested layer by layer and decorated layer by layer.
What is the difference between adapter mode and proxy mode?
The adapter pattern also looks a bit like the proxy pattern at first glance, right?
Adapters relate adaptors and proxies relate proxies, both of which satisfy the principle of composite reuse (using associations rather than inheritance). However, they do have significant differences, such as the role of the adapter to mediate between the old and new interfaces, and the role of the proxy to help do some extra work between the client and the proxy.