Design patterns

A better website about design patterns, UML

An overview of the

Design pattern is a solution to various problems commonly existing (recurring) in software design.

The seven principles

Single Responsibility Principle

A class should have only one reason to change. That is, a class has only one responsibility

For example, A class A is responsible for two different responsibilities, responsibility A1 and responsibility A2. If the requirements of responsibility A1 change and class A needs to be modified, the function of responsibility A2 that used to run normally may fail.

The Open-closed Principle — the general Principle

Software entities such as classes, modules, and functions should be open for extension and closed for modification

For example, here’s a company that makes computers that vary depending on the type of input.

Liskov Substitution Principle

All references to a base class must be able to transparently use objects from its subclasses. In plain English, the Richter substitution principle says that a subclass can extend the functionality of its parent class, but cannot change the functionality of its parent class.

For example, function P1 completed by class A needs to be extended. The extended function is P, where P consists of original function P1 and new function P2. If new function P is completed by subclass B of class A, subclass B may fail original function P1 while completing new function P2.

Dependence Inversion Principle

Upper-level modules should not depend on lower-level modules, they should all depend on abstractions. Abstraction should not depend on details, details should depend on abstractions. That is, interface-oriented programming, which relies on abstraction rather than on concrete. When you write code that uses a concrete class, you don’t interact with the concrete class, you interact with the upper interface of the concrete class.

For example, one day a product manager needs to add a new function that operates on a database. The logic that encapsulates the database operation and handles the business is typically written by a different programmer. Encapsulating database operations can be considered a low-level module, while processing business logic can be considered an upper-level module, so if processing business logic needs to wait until the code that encapsulates database operations is written before adding it, it will seriously slow down the project. The correct approach would be for the programmer handling the business logic to provide an abstract interface that encapsulates the database operations and hand it over to the programmer at the lower level, so that both sides can write it separately without affecting each other.

Interface Segregation Principle

A client should not rely on interfaces it does not need. Dependencies between classes should be established on the smallest interface. That is, there are no methods in each interface that subclasses cannot use but must implement; otherwise, the interface must be split. It is better to use multiple isolated interfaces than to use a single interface, where multiple interface methods are aggregated into one interface.

For example: class A and class B is implementing an interface I method of X, Y, Z, but class A method only need to use X, class B only need to use Y method, we should put interface into interface I1, I2 (only the method X) Y (only method), I3 (only method Z), and then let the class A and class B to different implementation interface I1 and I2

Law Of Demeter

Also known as the least-know principle, it states that one object should know the least about other objects. In layman’s terms, you only write to your immediate friends and don’t talk to strangers.

Group, for example, employees need to know the head office, branch information, head office directly to employee to fill in relevant information, from the head office and branch staff information, by the head office notice branch, branch to branch staff fill in the data, and then branch provided to the head office, rather than the corporation told one branch of the employees.

Composite/Aggregate Reuse Principle

Use object composition/aggregation rather than inheritance to reuse software. That is, use some existing objects in a new object and make them part of the new object. New objects reuse existing functionality by delegating to these objects.

For example, there are many employees with different roles in the company. The actual application code should be people, and then role successors, and then employees with different roles to implement roles, rather than direct successors of employees with different roles

Mnemonic method: single open li Yi connect di group

Creation pattern

The creative pattern provides a mechanism for creating objects, improving the flexibility and reusability of existing code.

Factory method pattern

The factory method pattern is a creative design pattern that provides a method to create an object in a parent class, allowing subclasses to determine the type of object to instantiate.

Take the getSystemService() method in the Activity as an example

@override public Object getSystemService(@servicename @nonNULL String name) {if (getBaseContext())  == null) { throw new IllegalStateException( "System services not available to Activities before onCreate()"); } if (WINDOW_SERVICE.equals(name)) { return mWindowManager; } else if (SEARCH_SERVICE.equals(name)) { ensureSearchManager(); return mSearchManager; } return super.getSystemService(name); }Copy the code

Abstract Factory pattern

The Abstract factory pattern is a creative design pattern that creates a series of related objects without specifying their concrete classes.

//Service is like a factory, Public class BaseService extends Service{@nullable @override public IBinder onBind(Intent Intent){return new Binder(); }}Copy the code

Generator mode

Generator pattern is a creative design pattern that allows you to create complex objects in steps. This pattern allows you to generate objects of different types and forms using the same creation code. Also called Builder mode, Builder mode.

// Display AlertDialog by creating icon, message step by step, New alertdialog.builder (this).seticon (r.map.ic_launcher).setMessage(r.string.app_name).show();Copy the code

The prototype pattern

The prototype pattern is a creative design pattern that allows you to copy existing objects without having to make your code dependent on the class to which they belong. Also known as clone mode

Parse ("smsto:10000"); // Copy the intent object Uri. Intent intent = new Intent(Intent.ACTION_SENDTO, uri); Intent newIntent = (Intent) intent.clone(); startActivity(newIntent);Copy the code

The singleton pattern

The singleton pattern is a creative design pattern that allows you to ensure that there is only one instance of a class and provide a global node to access that instance.

// getSystemService(), which uses WindowManager wm = (WindowManager)getSystemService(getApplication().WINDOW_SERVICE);Copy the code

Structural mode

The structural pattern describes how to assemble objects and classes into a larger structure while keeping the structure flexible and efficient.

Adapter mode

The adapter pattern is a structural design pattern that enables objects with incompatible interfaces to cooperate. Also called wrapper pattern.

// Create a recyclerview. AdapterCopy the code

The bridge model

The bridging pattern is a structural design pattern that splits a large class or series of closely related classes into two separate hierarchies of abstraction and implementation that can be used separately at development time.

Such as: For a View, there are two dimensional changes, one is the description of the View such as Button, TextView and so on, and the other dimension is actually drawing the View to the screen, which is related to Display, HardwareLayer and Canvas. These two dimensions can be regarded as the application of the bridging pattern.Copy the code

Portfolio model

The composite pattern is a structural design pattern that allows you to combine objects into a tree structure and use them as if they were individual objects.

For example: Android View structure is a tree structure, each ViewGroup contains a series of views, and the ViewGroup itself is a View. This is a very typical combination pattern in Android.Copy the code

Decorative pattern

Decorator is a structural design pattern that allows you to bind new behavior to an object by putting it into a special wrapper that contains behavior. Also called decorator pattern, decorator pattern.

For example, the Context is a nearly ubiquitous role in Android, ContextWrapper/ContextThemeWrapper is assumed in the process of inheriting the ContextImpl decorator role.Copy the code

The appearance model

The facade pattern is a structural design pattern that provides a simple interface to libraries, frameworks, or other complex classes. Also called facade mode.

For example, Context is the most important type. It encapsulates many important operations, such as startActivity(), sendBroadcast(), etc., and is almost a unified entry point for developers to operate applications. Context is an abstract class that defines only the abstract interface. The actual implementation is in the ContextImpl class.Copy the code

The flyweight pattern

Metadata is a structural design pattern that eliminates the need to store all data in each object and allows you to load more objects into limited memory by sharing the same state shared by multiple objects.

For example, the Message pool in the Handler messaging mechanism uses the share pattern to reuse Message objects. When using Message, message.obtain is commonly used to obtain messages. Using new Message() builds a large number of Message objects.Copy the code

The proxy pattern

The proxy pattern is a structural design pattern that allows you to provide substitutes for objects or placeholders for them. The proxy controls access to the original object and allows some processing before and after the request is submitted to the object. Also known as the delegate pattern.

For example, when an application accesses the interface methods of ActivityManagerService through ActivityManager, it is essentially accessed through proxy objects generated by IActivityManager, in a typical proxy pattern.Copy the code

Behavior patterns

Behavioral patterns are responsible for effective communication and delegation of responsibilities between objects.

Chain of Responsibility model

The chain of responsibility pattern is a behavior design pattern that allows you to send requests down a chain of handlers. Upon receipt of the request, each handler can either process it or pass it on to the next handler on the chain.

For example, when Android processes a click event, the parent View receives the click event first. If the parent View does not process the click event, it will be handed over to the child View and then passed down ~Copy the code

Command mode

Command pattern is a behavior design pattern that transforms a request into a single object that contains all the information associated with the request. This transformation allows you to parameterize methods, delay request execution, or queue them based on different requests, and implement undoable operations.

For example, in the Android event mechanism, the underlying logic forwards events. Each keystroke event is encapsulated as a NotifyKeyArgs object. Encapsulate specific event operations with InputDispatcher.Copy the code

Iterator pattern

The iterator pattern is a behavioral design pattern that lets you iterate through all the elements of a collection without exposing the underlying representation of the collection (lists, stacks, trees, etc.).

For example, Java has the Iterator class, which essentially uses the Iterator pattern. Android Cursor is also a Cursor.Copy the code

The mediator pattern

The mediator pattern is a behavior design pattern that allows you to reduce chaotic dependencies between objects. This pattern restricts direct interaction between objects, forcing them to collaborate through a mediator object.

For example, a ServiceManager and a Binder Driver act as intermediaries between a server and a clientCopy the code

Memo mode

The memo pattern is a behavioral design pattern that allows an object to be saved and restored to its previous state without exposing its implementation details.

For example, the Activity onSaveInstanceState and onRestoreInstanceState use the memo mode to save and restore, respectively.Copy the code

Observer model

The Observer pattern is a behavior design pattern that allows you to define a subscription mechanism that notifies multiple other objects that “observe” an object when an event occurs.

For example, ContentObserver in Android watches (catches) changes to the database caused by a particular Uri and does something about them.Copy the code

The state pattern

State mode is a behavior design mode that allows you to change the behavior of an object as its internal state changes, making it look like it’s changing the class it belongs to.

For example, WIFI management module. When WIFI is on, it automatically scans the surrounding access points and displays them in the form of a list. Empty when wifi is off. The wifi management module performs different behaviors according to different states.Copy the code

The strategy pattern

The strategy pattern is a behavior design pattern that allows you to define a series of algorithms and place each algorithm in a separate class so that the objects of the algorithm are interchangeable.

For example, different interpolators can be set to the Animation object to achieve different Animation effectsCopy the code

Template method pattern

The template method pattern is a behavior design pattern that defines the framework of an algorithm in a superclass, allowing subclasses to override specific steps of the algorithm without modifying the structure.

For example: The Activity in Android, the entire implementation process is actually a framework is the same, the specific implementation is a subclass to complete.Copy the code

Visitor pattern

The visitor pattern is a behavior design pattern that isolates an algorithm from the object it works on.

For example, Android's compile-time annotations are a visitor pattern. The core principle of compile-time Annotation relies on APT (Annotation Processing Tools).Copy the code

Interpreter mode

The interpreter pattern is a behavior design pattern that, given a language, defines its syntax, and defines an interpreter that parses the language.

For example, androidmanifest.xml defines the attributes and sub-tags of tags such as <Activity> and <Service>, specifying the usage (syntax), and parsing through the PackageManagerService (interpreter).Copy the code