preface

Design patterns are useful abstract tools for solving design problems in fields such as engineering and architecture. For the same purpose, the software development world has borrowed the concept that a design pattern is a design template for an object or class that solves a problem that occurs frequently in a particular domain. This paper is divided into 8 parts and involves 22 design modes:

  • Object Creation (1 to 6)
    • The prototype pattern
    • Simple Factory model
    • The factory pattern
    • Abstract Factory pattern
    • Builder (generator) pattern
    • The singleton pattern
  • Interface adaptation (7 to 9)
    • Adapter mode
    • The bridge model
    • The appearance model
  • Object decoupling (10 to 11)
    • The mediator pattern
    • Observer model
  • Abstract Set (12~13)
    • Portfolio model
    • Iterator pattern
  • Behavior expansion (14 to 16)
    • Visitor pattern
    • Decorator pattern
    • Chain of Responsibility model
  • Algorithm Encapsulation (17~19)
    • Template method pattern
    • The strategy pattern
    • Command mode
  • Performance and Object Access (20 to 21)
    • The flyweight pattern
    • The proxy pattern
  • Object State (22)
    • Memo mode

Object creation

First, prototype mode

  1. What is a prototype pattern? Use a prototype instance to specify the kind of object to create, and create a new object by copying this object.

The prototype pattern is essentially creating another customizable object from an object into a template without knowing any of the creation details.

  1. When to use prototype patterns?

    • The objects that need to be created should be independent of their type and how they are created.
    • The classes that need to be instantiated are determined at run time.
    • You don’t want a factory level that corresponds to the product level.
    • The difference between instances of different classes is simply a combination of states. Therefore, it is more convenient to copy the corresponding number of prototypes than to manually instantiate them.
    • Classes are not easy to create, such as composite objects where each component can have other components as child nodes. It is much easier to copy an existing composite object and modify the copy.
  2. Deep copy and shallow copy

    • Shallow copy, pointerlevel copy, in which the copied instance still points to the source memory space, and any modification of the original instance or the copied instance will affect the other (because the pointer points to the same memory).
    • Deep copy, memory-level copy, opens up new memory space and modifies the original instance or copied instance, leaving the other unaffected.

    The default -copy in iOS is shallow copy. To make a deep copy, follow the

    protocol and override the -copyWithZone method.

2. Simple factory model

  1. What is the Simple Factory pattern? The Simple Factory Pattern is also known as Static Factory Method. In the Simple Factory Pattern, instances of different classes can be returned according to different parameters. The simple factory pattern specifically defines a class that is responsible for creating instances of other classes, which usually have a common parent class.
  2. Advantages of the simple factory pattern
    • Separating object creation from the business processing of the object itself reduces the coupling of the system, making both relatively easy to modify.
    • When you need something, just pass in the right argument and you can get the object you need without knowing the details of its creation.
    • When calling the factory method of a factory class, because the factory method is static, it is easy to use, can be directly called by the class name, and only need to pass in a simple parameter, modify the parameter without modifying any source code.
  3. Disadvantages of the simple factory pattern
    • The biggest problem of the simple factory model is that the responsibilities of the factory class are relatively heavy. Adding new products requires modifying the judgment logic of the factory class, which is contrary to the open and closed principle.

Simple Factory Mode Demo (Calculator)

3. Factory model

  1. What is the factory model? Define an interface for creating objects and let subclasses decide which class to instantiate. The factory method delays instantiation of a class to subclasses.

  2. When to use factory mode?

    • The classes that you need to create objects for cannot be accurately predicted at compile time.
    • Class wants its subclasses to decide what type of instance to create at run time.
    • Class has several helper classes as subclasses, and you want to localize which subclass to return.
  3. The advantage of the factory pattern is that creating objects using the factory method is the best approach compared to creating concrete objects directly. Factory methods allow clients to demand that objects created by factory methods have a common set of behaviors. Therefore, introducing a new concrete product into the class hierarchy does not require modifying the client code, because the interface of any concrete object returned is the same interface that the client has always used.

  4. Factory methods in Cocoa Touch factory methods are used very extensively in Cocoa Touch, so NSNumber, for example, provides a lot of methods to create things like -numberWithbool and -numberWithInt and they pass in different types of arguments, Get an NSNumber instance.

Factory Mode Demo (Calculator)

Abstract factory

  1. What is an abstract factory? Provides an interface for creating a series of related or interdependent objects without specifying their concrete classes.

    If you have multiple classes that share the same behavior but have different implementations, you may need some abstract type as their parent class to extract their common behavior into the parent class.

    For example, we know what a regular pizza looks like and can anticipate what’s coming when we order it. When we say “go out for pizza”, the word “pizza” is an abstract type that defines the characteristics that a pizza should have in common. However, the taste of the same pizza (Italian pizza, sausage pizza) varies greatly from place to place. Because there are so many types of pizza, we simply call it “pizza” for this particular type of food.

    The class method of the superclass -getFactory simply returns the concrete (appropriate) factory class. Its subclasses should not override this method. The -getFactory method returns a concrete factory instance based on the configuration.

  2. The two are similar in many ways. They both serve the same purpose: creating objects without letting the client know the details of the creation. The comparison is as follows:

The abstract factory The factory pattern
Create a way Object composition creates abstract products Class inheritance creates abstract products
Create categories Create multiple series of products Create a product
How to extend Modify the interface of the parent class to support new products The subclass creator overrides the factory method to create a new product

Image factory Demo (map engine)

Builder (generator) mode

  1. What is the Builder pattern? The builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.

    It can separate the internal representation of a product from the process of product generation so that a construction process can generate product objects with different internal representation. If we use the Builder pattern, users can just specify the type to build and get their object instances, regardless of the build process and details.

    In this pattern, in addition to the user and the product they need, there are two important roles: Director and Builder.

    • The Director knows what the Builder should build, and the parameters give it the missing information to create a specific product.
    • Builder is an abstract interface that declares a -build method implemented by ConcreBuilder to construct the actual product. ConcreBuilder has a -getresult method that returns the built result to the client.
  2. When to use builder mode

    • You need to create complex objects that involve various parts. The algorithm for creating objects should be independent of how the parts are assembled. A common example is building composite objects.
    • The build process needs to build objects in different ways (for example, parts or combinations that represent different things).
  3. Comparison between the Builder pattern and The Abstract Factory Abstract factories and the Builder pattern have many similarities in terms of abstract object creation, but they are very different.

    • The Builder pattern focuses on creating complex objects in steps, and many times objects of the same type can be created in different ways. Builder mode returns the product at the end of the multi-step creation process.
    • Abstract factories focus on creating suites of simple or complex products. The abstract factory returns the product immediately.
    Builder model The abstract factory
    The complexity of the image Building complex Objects
    Required steps Multi-step create
    Creation Mode Type Multiple ways to create
    The timing of the return object The last step in the creation process
    Create the results Focus on a specific product
  4. The summary generator pattern can help build objects that involve various combinations of parts and representations. Without this pattern, a Director who knows the details needed to build an object could end up with an extremely complex class. With countless embedded algorithms for building various representations of the same class. These algorithms are supposed to be independent of the components of the object and their assembly process.

Builder Mode Demo (Draw cartoon characters)

Singleton mode

  1. What is the singleton pattern

    Singleton pattern: Ensures that a class has only one instance and provides a global access point to access it.

    The singleton pattern is almost the simplest of all design patterns. Its intent is to make an object of the class a unique instance in the system. To do this, start by instantiating it on the client side. Therefore, a mechanism that allows only a unique instance of an object class to be generated is needed to “block” all access to the object that you want to generate.

  2. When to use the singleton pattern

    • Classes can have only one instance, and they must be accessed from a well-known access point, such as a factory method.
    • This unique instance can only be extended by subclassing, and the extended object does not break the client code.
  3. Objective-c implementation singleton pattern In OC, there are currently two implementations of singleton pattern:

    • The original implementation

      Comply with the<NSCopying>Agreement to rewrite-allocMethods and-copyMethod, consider thread safety.
    • The GCD implementation

      With the help of the GCDdispatch_onceimplementation

Singleton pattern Demo(a rigorous singleton)

The interface adapter

Seven, adapter

  1. What is the adapter pattern

    The adapter pattern is used to connect two different kinds of objects so that they work together without problems. The idea is simple: The adapter implements the behavior of a certain interface that the client needs, and at the same time, it connects to an object that has (completely) different interface behavior. An adapter lies between a target interface that the client knows how to use and an adapter that the client knows nothing about. Its main function is to transmit the behavior of the adaptor to the client at the other end of the pipe.

    Definition: To convert the interface of a class to another interface that the customer wants. The Adapter pattern makes it possible for classes with incompatible interfaces to work together.

  2. Adapter classification

    • Class adapter is implemented through class inheritance, and Objective-C has the language feature Protocol, so in Objective-C, classes can implement the Protocol and inherit from the parent class, so as to achieve the effect of multiple inheritance in C++. To implement a class adapter in an OC, you first need to have a protocol that defines a set of behaviors to be used by the client, and then implement this protocol with a concrete adapter class that also inherits the adaptor.

    • Object adapters differ from the class adapters above in that they do not inherit the adaptor, but instead compose a reference to it.

  3. Comparison of class adapters to object adapters

    The class adapter Object adapter
    Adaptee to target for a single specific Adaptee class Can accommodate multiple adaptees and subclasses
    Easy to override the behavior of Adaptee as if it were directly subclassed It is difficult to override and requires the subclass object rather than the Adaptee itself
    There is only one Adaptee object, no additional town indirectly accessing the Adaptee Additional Pointers are required to access the Adaptee indirectly and to match its behavior

    Adaptee: Target: indicates the Target interface

  4. When to use the adapter pattern

    • The interface of the existing class does not match the requirements
    • You want a reusable class that can work with other classes that may have incompatible interfaces.
    • If you need to adapt several different subclasses of a class, but it is not practical for each subclass to subclass a class adaptation, you can use an object adapter (delegate) to adapt the interface of its parent class.

Bridge mode

  1. What is bridge mode? Separate the abstract part from its implementation part so that they can all change independently.

    By separating an abstraction from its implementation, I do not mean separating an abstract class from its derived class, because that makes no sense. Implementation refers to the object that an abstract class and its derived classes use to implement themselves.

    There may be multiple classifications when implementing the system, and each of these classifications may change, so separate these classifications out and let them change independently, reducing the coupling between them.

  2. Synthesis/polymerization reuse principle

    • Disadvantages of inheritance The inheritance of objects is already defined at compile time, so there is no way to change the implementation of inheriting from a parent at run time. The implementation of a subclass is so closely dependent on its parent that any change in the superclass implementation must result in a change in the subclass. When subclasses need to be reused, if the inherited implementation is not suitable for the new problem, the parent class must be overridden or replaced with another class that is more suitable. This dependency limits flexibility and ultimately reusability.

    • Principles of Synthesis/Polymerization Reuse Synthesis (also called Composition, Aggregation) and Aggregation are special types of association. Aggregation represents A weak “owning” relationship in which an object A can contain an object B, but the object B is not part of an object A; Composition, on the other hand, is a strong “ownership” relationship, which embodies a strict relationship between the parts and the whole, with the same life cycle of the parts and the whole.

      For example, the goose has two wings, and the wings and the goose are part and whole, and their life cycle is the same, so the goose and the wings are a synthetic relationship. Geese live in groups. Each goose belongs to one group. There can be more geese in one group.

    Prioritizing composition/aggregation of objects will help keep each class encapsulated and focused on a single task. This class and class inheritance hierarchy will remain small and unlikely to grow into an uncontrollable behemoth.

  3. When to use bridge mode

    • Don’t want to have a fixed binding between abstraction and implementation (so you can switch implementations as needed at run time)
    • Both the abstraction and its implementation should be independently extensible by subclassing.
    • Changes to the abstract implementation should not affect the client code.
    • If each implementation requires additional subclasses to refine the abstraction, then it is necessary to split them into two parts.
    • You want to share an implementation between multiple objects with different abstract interfaces.

Bridge Mode Demo (Mobile phone software System)

9. Appearance mode

  1. What is a facade pattern definition: To provide a unified interface for a set of interfaces in a system, the facade defines a high-level interface to make subsystems easier to use.

    The facade pattern provides a unified interface for a set of different interfaces in a subsystem. The facade defines the upper-level interfaces that make subsystems easier to use by reducing complexity and hiding communication and dependencies between subsystems.

  2. When to use appearance mode

    • Subsystems are becoming increasingly complex. Many classes evolve as patterns are applied. You can use the facade pattern to provide a simpler interface to these subsystem classes.
    • You can layer the subsystem using skins. Each subsystem level has a facade as an entry point. Having them communicate through their appearance simplifies their dependencies.
  3. As programs grow larger and more complex, more and more smaller classes evolve from design and application patterns. Without a simplified way to use these classes, the client code becomes increasingly complex, difficult to understand, and difficult to maintain, and the facade helps provide an easier way to use these classes in the subsystem. The default behavior for handling these subsystems may be simple methods defined in the facade, without having to use these classes directly.

Appearance Mode Demo (Passenger Riding Case)

Object decoupling

10. Intermediary model

  1. What is the definition of the mediator pattern: an object encapsulates how a series of objects interact. The mediator loosens the coupling of objects by eliminating the need to explicitly refer to each other, and can change their interactions independently

    Object-oriented design encourages the dispersal of behavior among different objects, and this dispersal can lead to interrelationships between objects. In the worst case, all objects understand and interoperate with each other.

    Although the dispersal of behavior across different objects increases reusability, the increased interconnectedness reduces the benefits gained. Increased association makes exclusivity difficult or impossible to work without relying on other objects. The overall behavior of an application can be difficult to change because it is distributed across many objects.

    The mediator pattern is used to solve such problems by defining a centralized place where interactions between objects can be handled within a mediator object, and other objects do not have to interact with each other, thereby reducing the dependency between them.

  2. When to use the mediator pattern

  • Interactions between objects are well-defined but complex, resulting in a set of objects that are interdependent and difficult to understand.
  • Objects are difficult to reuse because they reference and communicate with many other objects.
  • You want to customize a logic or behavior that is distributed across multiple classes without generating too many subclasses.
  1. Advantages and disadvantages of the mediator pattern The mediator pattern is both easy to use in a system and easy to misuse. When the system has a complex many-to-many interaction object group, do not rush to use the intermediary pattern, but to rethink the design of the system is reasonable.

    • Advantages: 1, the existence of intermediary, reduce the coupling degree of each specific class, so that each specific class and intermediary can change and reuse independently;

      2, because of the abstraction of how objects cooperate, the intermediary is regarded as an independent concept and encapsulated in an object, so that the object of concern is transferred from the behavior of each object to the interaction between them, that is, to look at the system from a more macroscopic perspective.

    • Disadvantages: Since the mediator controls centralization, the interaction complexity becomes the complexity of the mediator, which makes the mediator more complex than any concrete class.

  2. In summary, intermediary mode is widely used, and componentization should be the most appropriate application scenario of intermediary mode. Each component is independently developed and maintained, and middleware is used for communication between components. See: iOS a lightweight componentization idea

    While the mediator pattern is useful for dealing with situations where the behavior of the system is scattered across different objects and the objects are interdependent, care should be taken to avoid making the mediator class too large to maintain. If this is already the case, consider using another design pattern to break it down.

Mediator Mode Demo (Colleague Dialogue)

The observer model

  1. What an observer pattern definition is: Defines a one-to-many dependency between objects, where all dependent objects are notified and automatically updated when an object’s state changes

    The observer model is also called the publish-subscribe model. The Observer subscribes to notifications from the Subject. ConcreteObserver Implements the abstract Observer and overloads its update method. Once an instance of Subject needs to notify an Observer of any changes, Subject sends an Update message notifying all registered Observers stored in the internal list. In the actual implementation of the ConcreteObserver update method, the Subject’s internal state can be retrieved and processed later.

  2. When to use observer mode

    • There are two abstract types that depend on each other. By encapsulating them in their own objects, they can be changed and reused separately.
    • Changes to one object require changes to other objects at the same time, without knowing exactly how many objects need to be changed.
    • One object must notify other objects, and it does not need to know what the other objects are.
  3. Observer mode in Cocoa Touch framework

    • Notifications A one-to-many publish-subscribe pattern is implemented in the Cocoa Touch framework using NSNotificationCenter and NSNotification objects, which allow topics to communicate with observers in a loosely coupled manner. The two can communicate without knowing much about the other.

    • Key-value observation Cocoa provides another mechanism called key-value observation through which objects can be notified of other object-specific changes. This mechanism is especially important in MVC(Model-View-Controller) pattern scenarios, which allow View objects to observe changes to Model objects through the Controller layer.

      know Key-value observation
      The central objects provide change notification to all observers The object being observed sends notifications directly to the observer
      Focus on program events in a broad sense A value bound to a specific object property

Abstract set

Xii. Combination mode

  1. What is a composite pattern definition: Grouping objects into a tree structure to represent a parties-whole hierarchy. The composite pattern makes the use of single objects and composite objects consistent.

    The composite pattern allows us to combine objects of the same base type into a tree structure, where the parent node contains children of the same type. In other words, the tree forms a parties-whole hierarchy.

    A tree structure is a hierarchy that contains both a combination of objects (containers) and a single pair of objects as leaf nodes (primitives). The nodes contained in each assembly can be leaf nodes or other assemblies. This relationship repeats recursively in this hierarchy. The client has the same operation on the composite node and leaf node, and the client can ignore the difference between them when using them.

  2. When to use composite patterns

    • You want to get the tree structure (partial-whole hierarchy) of the object abstraction.
    • You want the client to handle all objects in the composite structure uniformly.
  3. Transparent and secure

    • Transparent methods also have -add and -remove methods on leaf nodes, but these behaviors are not required on leaf nodes; The idea is that they have exactly the same interface, and that the caller has to deal with the logic completely, which is transparent.

    • If you don’t want the above methods to exist on the leaf node, you can avoid transparent proxy problems by declaring a Composite structure that manages the methods of subclass objects instead of the -add and -remove methods in the basic Component. Due to the lack of transparency, leaves and branches have different interfaces, and the client calls need to make corresponding judgments, which brings inconvenience to the caller.

    There is no absolute superiority or inferiority between the two methods, depending on personal understanding and trade-offs (analogy between simple factory and factory mode).

Portfolio Model Demo (Corporate Organizational Structure case)

Iterator pattern

  1. What is an iterator pattern definition: Provides a way to access the elements of an aggregate object sequentially without exposing the exclusive internal representation.

    Iterators provide a way to sequentially access elements in an aggregate object (collection) without exposing the underlying representation and details of the structure. The function of traversing the elements in the collection is transferred from the collection itself to the iterator object. An iterator defines an interface for accessing a collection element and logging the current element. Different iterators can perform different traversal strategies.

  2. When to use the iterator pattern

    • You need to access the contents of a composite object without exposing the internal representation.
    • You need to traverse a composite object in a number of ways.
    • You need to provide a unified interface for traversing various types of composite objects.
  3. Iterator pattern in Cocoa Touch

    • NSEnumerator as of iOS2.0, you can use NSEnumerator to enumerate elements in NSArray, NSDictionary, and NSSet objects.
    • Block-based Enumeratoration block-based Enumeratoration is introduced in iOS4
    • Quick enumeration (for-in)
    • Internal enumeration

      NSArry has an instance method-makeObjectsPerformSelector:, which allows a client to send a message to each element in the array, telling each element to execute the specified method.

Iterator mode Demo (Passenger ticket case)

Behavior extension

The Visitor pattern

  1. What is a visitor pattern definition: Represents an operation that acts on elements in an object structure. It allows you to define new operations on elements without changing their classes.

  2. When to use the visitor pattern

    • A complex object structure contains many other objects with different interfaces, and the implementation of the object depends on its specific type of operation.
    • You need to do a lot of unrelated operations on objects in a composite structure, but you don’t want those operations to “contaminate” the classes of those objects. You can put the related operations together, define them in a visitor class, and use them when you need to define operations in visitors.
    • Classes that define complex structures rarely change, but often need to add new operations to them.
  3. Summarizing the visitor pattern is a powerful way to extend the capabilities of composite structures. The Visitor pattern can be used if the composite structure has well-designed basic operations and the structure is relatively stable.

Visitor Model Demo (Men and Women case)

15. Decorator mode

  1. Decorator pattern: Dynamically adds some additional responsibilities to an object. Decorator pattern is more flexible than subclassing in terms of extending functionality.

    Component defines an interface to objects to which responsibilities can be dynamically added. ConcreteComponent: ConcreteComponent defines a concrete object. You can also add responsibilities to this object. Decorators, the Decorator abstract class, extend the functionality of the Component class from an external class, but there is no need for Component to know about the Decorator. Concretedecorators are concrete decorators that add responsibilities to components.

    In daily development, the use of class inheritance should be reduced. Excessive use of class inheritance can lead to a large number of classes that become difficult to maintain, while using composition can make our system more resilient, easier to modify and extend.

  2. When to use decorator mode

  • You want to add responsibilities to a single object in a dynamic, transparent way without affecting other objects.
  • You want to extend the behavior of a class, but can’t. Class definitions may be hidden and cannot be subclassed; Alternatively, an extension of each behavior of a class will result in a large number of subclasses to support various combinations of capabilities.
  • Extensions to the responsibilities of a class are optional.
  1. Change the “look” and “content” of the object

    Change in “appearance” (decorator) “Content” change (Policy)
    Change from outside Change from within
    Each node is unaware of the change Each node knows a predefined set of changes

Decorator mode Demo (filter images)

16. Responsibility chain model

  1. What is the chain of responsibility model

    Definition: To avoid coupling between the sender and receiver of the request by giving multiple objects the opportunity to process the request. This pattern chains these objects together for a day and passes requests along the chain until an object processes it.

    The chain of responsibility pattern allows you to add or modify the structure of processing a request at will, increasing the flexibility of assigning responsibility to an object. However, the possibility that a request may not be processed at the end of the chain of responsibility, or may not be processed because it is not configured correctly, requires consideration.

  2. When to use the chain of responsibility model

    • There are multiple objects that can handle requests, and the handler can only be determined at run time.
    • Makes a request to a set of objects without wanting to show the specific handler that specifies the request.
  3. conclusion

    The chain of responsibility model can solve a large number of branch judgments and effectively reduce the logical complexity of client calls. All three design patterns extend the behavior of objects with minimal or no modification. It has great reference significance for the more and more complex system extension.

Responsibility Chain Model Demo (Salary increase case)

Algorithms encapsulation

17. Template method pattern

  1. What is a template method pattern

    Definition: Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. The template method allows subclasses to redefine some y-specific steps of the algorithm without changing the structure of the algorithm.

    The basic idea is to define a “standard” algorithm in a method of an abstract class. The implementation of this method is implemented by subclass overloading. This method is called a “template” because the algorithm defined by the method lacks some specific operations. Subclasses override base operations to provide unique operations for template methods to use.

  2. When to use the template method pattern

    • You need to implement the invariant parts of the algorithm once and leave the mutable behavior to subclasses.
    • The common behavior of subclasses should be extracted and placed in common classes to avoid code duplication. Differences in existing code should be separated into new operations. The different code is then replaced with a template method that calls these new operations.
    • To control the extension of subclasses, you can define a template method that calls a “hook” operation at a particular point. Subclasses can extend functionality at these points by operating on hooks.
  3. Template methods vs adapters

Template method Adapter (delegate) pattern
The parent class defines a general algorithm but lacks some specific/optional information or algorithm, and it acts as a “recipe” for an algorithm through this missing information or algorithm The adapter defines a specific algorithm along with a predefined delegate interface
The missing information is implemented by subclasses via inheritance A particular algorithm is provided by any combination of objects

Template method Mode Demo(Making multiple sandwiches)

18. Strategic mode

  1. A policy pattern defines a family of algorithms, encapsulates them separately so that they can be replaced with each other. This pattern allows the algorithm to change without affecting the clients using the algorithm

    A key role in the policy pattern is the policy class, which declares a common interface for all supported related algorithms. In addition, there are concrete policy classes that use policy interfaces to implement pre-close algorithms. The object of the Context class is configured with an instance of a concrete policy object that uses the policy interface to invoke the algorithm defined by the concrete policy class.

  2. When to use policy patterns

    • A class uses multiple conditional statements in its operations to define many behaviors. We can move the related condition branches into their own policy classes.
    • Variations of the algorithm are required.
    • Complex, algorithm-specific data structures need to be exposed to the client.
  3. In the MODEL-View-View Controller (MVC) pattern, the controller determines what and when a view displays model data. The view itself knows how to draw, but it needs the controller to tell it what to display. If a view works with different controllers, the output format of the data may be the same, but the type and format of the data may vary with the output of different controllers. Therefore, the controller in this case is the view’s policy. The relationship between controller and view is based on policy pattern.

  4. The summary strategy pattern is somewhat similar to the decorator pattern. Decorators extend the behavior of objects from the outside, and policies are encapsulated within objects. So decorators change the “appearance” of objects and strategies change the “content” of objects.

Strategic Model Demo (Shopping mall discount case)

Command mode

  1. What is the Command mode

    A command object encapsulates information about how to execute instructions on a target, so a client or caller can still perform any known operation on it without knowing any details about the target. By encapsulating the request as an object, the client can parameterize it and put it in a queue or log, as well as support undo operations. The command object binds one or more actions to a specific sink. Command mode eliminates the binding between the action as an object and the receiver that executes it.

    Definition: Encapsulating a request as an object that can parameterize a client with different requests, queue requests, or log requests to support undoable operations. The command pattern separates objects that request an action from objects that know how to perform an action. Right

  2. When to use command mode

    • You want your application to support undo and restore.
    • You want to parameterize an action with an object to perform the operation and replace the callback function with a different command object.
    • You want to specify, rank, and execute requests at different times.
    • You want to log changes so that in the event of a system failure, those changes can be redone later.
    • To enable a system to support transactions, transactions encapsulate a series of changes to data. Transactions can be modeled as command objects.
  3. Advantages of command mode

    1. Make it easier to design a command queue (Waiter’s commandList array)
    2. Commands can be easily logged if needed (in Waiter’s setOrder)
    3. Allows the party receiving the command to decide whether or not to reject the command (the Cooker class can notify Waiter that the command is not available)
    4. Requests can be undone, modified, and redone (number of commands can be modified)
    5. Adding a new concrete command class is easy because it does not affect other classes

Command mode Demo (Barbecue shop order operation)

Performance and object access

20. Enjoy yuan mode

  1. What is the share mode

    Definition: Use sharing techniques to efficiently support a large number of fine-grained objects

    Implementing the share pattern requires two key components, usually shareable share objects and the pool that holds them. Some central object maintains this pool and returns the appropriate object instance from it. A factory is an ideal candidate for this role, which returns various types of concrete share objects through a factory method.

    The meta-share pattern avoids the overhead of a large number of very similar classes. In programming, it is sometimes necessary to generate a large number of fine-grained class instances to represent data. If you can find that these instances are essentially the same except for a few parameters, you can sometimes drastically reduce the number of classes you need to instantiate. If you can move those parameters outside the class instance and pass them in when the method is called, you can dramatically reduce the number of instances through sharing.

  2. When to use the free mode

    • Applications use many objects
    • Keeping objects in memory affects performance
    • Most of the specific state of an object can be placed externally and lightened
    • Once the external state is removed, the original set of objects can be replaced with fewer shared objects
    • Applications do not rely on object identifiers because shared objects cannot provide unique identifiers

21. Agency mode

  1. What is the Proxy model

    Definition: Provides a proxy for other objects to control access to that object.

    The idea of the proxy pattern is to use a proxy that basically behaves like an entity object, and clients can use the proxy “transparently” without knowing that they are dealing with a proxy rather than an entity object. In iOS, proxies are used to decouple.

    Use proxies to pass View layer events to controllers

    Implement the tableView delegate and dataSource into a separate Model or ViewModel

  2. Classification of agents

    • Remote proxies provide local representation for objects that reside in different address Spaces or on a network
    • Virtual proxy creates heavy objects as required
    • Protection Proxy controls access to original objects based on access permissions
    • Intelligent Reference Proxy (SAMRT-Reference Proxy) manages memory through technical references to real objects and is also used to lock real objects so that they cannot be modified by other objects.

8. Object status

22. Memo Mode

  1. What is the Memo mode?

    Definition: To capture the internal state of an object and save the state outside of the modified object without breaking encapsulation. This allows you to later restore the object to its original saved state.

    Memo mode has three roles: originator, memento, and caretaker.

    • The originator is responsible for creating a Memento that records the internal state of the current moment and can be used to restore the internal state. Originator Memento stores the internal state of originator as required
    • Memento is responsible for storing the internal state of originator objects and preventing objects other than Originator from accessing memento.
    • The caretaker keeps the Memento and cannot check or modify it.
  2. Use the memo pattern appropriately

    • You need to save the state of an object (or part of it) at a point in time, providing the state to be restored to that point later.
    • The interface used to get the state exposes implementation details that need to be hidden from the outside.

Memo mode Demo (save game progress to restore)