Factory model and OO design principles

Source: Internet
Author: User

If creation is regarded as a responsibility, which object in the system should have this responsibility? If we regard creation as knowledge, where should we place the creation knowledge? Speaking of our responsibilities, we have to talk about the famous GRASP principles:

GRASP is short for General Responsibility Assignment Software patterns. It contains nine modes, as shown below:

1. Creator: determines who should create the object.

2. Information expert: This model is used to determine how to assign responsibilities to objects. Generally, roles are assigned to objects that contain information about this role. This also reflects the high cohesion model.

3. Low coupling)

4. Controller ).

5 High Cohesion)

6 polymorphism (polymorphism)

7 pure fabrication)

8. indirection)

9 protected variations)
It can be seen that GRASP is very concerned with who created the object and provides a responsibility Allocation Solution Model: Information EXPERT mode; we do not have to go into the details of GRASP, we can get the following inspiration from the above statement:

  • The creation of objects is not random, and there are standards that can be followed, from which we can get flexibility and maintainability;
  • Responsibilities are assigned to the information experts related to this role, that is, the most suitable person to do the most appropriate thing.

 

When the knowledge of creating an object is distributed across the system, the spread of this phenomenon actually shows the confusion of Responsibility Assignment in system creation, there is a lack of information experts who have created knowledge (please note the descriptions here ). The creation logic is usually like this. It contains a series of if-else judgment logic, which determines the creation of Objects Based on specific runtime parameters. If this part is definite, we don't have to worry too much about it. However, if it is changed, such as deleting the creation of an object or adding a new type of creation, this part of code will be frequently modified, this modification actually indicates that we have violated the OCP principle (disable modification and enable expansion), so we must extract and isolate this part based on the principle of identifying changes in encapsulation.
Looking at all the books related to design patterns, we can see this statement:

The factory mode is dedicated to instantiating a large number of classes with common interfaces. The factory mode dynamically determines the class to be instantiated during running.

It seems that the factory model is exactly what we need, but we are not eager to start. Is there another way, [interface? The book "Java and mode" provides such an interface implementation method.

I am used to understand interfaces as contracts and actions, and create different objects. The differences between objects and actual behaviors are actually different. Is the interface okay? Suppose I have used the interface and solved the problem? No! New classes are also subject to code modification issues. This method only transforms the form of the problem and does not really solve the problem. Using Interfaces we lose the advantage of code reuse, while using interfaces in a large number of specific classes is not a good idea, although Java and patterns all use interfaces for implementation. If the object to be created does not have a common business logic, you can use an interface to assume the role of an abstract product. But more often, there is a common business logic between products, then these logics should be moved to the abstract role.
In fact, we will create a knowledge set and set up an information expert responsible for object creation. The simple factory model is our first information expert with creation knowledge:
Simple Factory
The simplest extraction and isolation method is to use [

Simple Factory

]. A simple factory is characterized by parameterized object creation. A simple factory must know each product and when to provide it to the Client. Some people will say that the simple factory still needs to change the medicine without changing the changes. This part of code still needs to be modified when adding new classes! Indeed, what benefits have we gained? Centralized changes! This well complies with the DRY principle (Don't Repeat Yourself !) The creation logic is stored in a single location. Even if it changes, we only need to modify one location. DRY is simple, but it is the key to ensuring that our code is easy to maintain and reuse. The DRY principle also reminds us that the system functions are well divided! The clear division of duties ensures the uniformity of code to a certain extent. This sentence is of great guiding significance to our subsequent analysis. After all, simple factories only reuse code at a low level.

Digress: simple factories are simple, but the DRY principle behind them has benefited us a lot in practice. Last year, I worked with my partner to upgrade the site and wrote a lot of repeated code; code duplication and chaotic source code organization. Failure to make proper planning and responsibility analysis is the original sin. In this year's new project, the DRY principle is the sword of damaklis above my head. It is an important standard for me to organize and manage projects without repeating things.
Summary of the phases of the simple factory model:

  • Identifying changes to isolate changes. A simple factory is an obvious implementation method.
  • A simple factory places the creation knowledge in a single location and conforms to the DRY
  • The client does not need to understand the object creation process. To some extent, OCP is supported.
  • Adding a new product may cause modifications to the creation code. This indicates that the simple factory mode does not support the OCP.
  • The simple factory class integrates all the instance creation logic, which easily violates the High Cohesion responsibility allocation principle.
     
Factory Method mode

The simple factory mode does not provide enough support for OCP because it has a lot of knowledge: How many products are there and when to create products. In other words, simple factories assume too many responsibilities. The DRY principle prompts us to clearly draw the line of responsibility of the object. One way is to delegate power and hand over the created knowledge to sub-classes. The submission of knowledge means the transfer of duties.
After doing so, we re-examine the relationship between classes: the Core factory class is no longer responsible for the creation of all products, and the level of the core class rises to become an abstract factory role, only interfaces that must be implemented by specific sub-classes are provided, regardless of the Creation details of specific products. The created knowledge is owned by a specific factory. At this time, a parallel hierarchical structure, the hierarchical structure of the product family, and the corresponding factory hierarchical structure appear in the system.
A simple factory places the core on a specific class. The Factory Method mode focuses on the abstract class, and the specific Factory class inherits the creation behavior. The specific factory has the same interface, so there is another example called the multi-state factory mode. This is where our focus has shifted from implementation to "interface": focusing on motivation rather than implementation is the basic OO design principle, hiding implementations after interfaces actually decouples object implementations from their objects. From the perspective of "dependency", the dependencies in the system are no longer specific implementations, but abstract. This is the DIP principle: High-Level modules should not depend on low-level modules, both of which should depend on abstraction. This principle implies that objects are only coupled at the conceptual level and cannot be coupled at the implementation level!

The application of the factory method model must fully abide by the principle of the lining replacement. That is, the application of the factory method mode can become possible only when the parent class can be replaced with a subclass.
To add a new product, you only need to add this product class and its factory class. There is no need to modify the Client and existing factory code. Factory Method fully supports the OCP principle.

Abstract Factory Model


The abstract factory provides an interface to the client so that the client can create product objects in the product family without specifying the specific product type. This is the intention of the abstract factory. Abstract Factory problems are the system design of multi-level product hierarchy. The biggest difference between the abstract factory and the factory method mode is that the latter only targets a product level structure, while the abstract factory faces multiple levels.

Similarly, we have done an excellent job of decoupling applications from specific implementations. The factory method uses inheritance, while the abstract factory uses a combination of objects. The abstract factory provides an abstract type of a product family. This subclass completes product creation.
The expressions of ocp dip lsp and other principles mentioned in the factory method mode also apply to the abstract factory mode.
I once mentioned in the article "the power of perspective-let's talk about OO design principles" that abstract high-level policies requires stability. Abstract Factory, as a high-level abstraction, has a huge impact if its interface changes: All subclasses must be modified! This requires the abstract factory interface design to be highly abstract!
 

Summary:

  • Detecting changes, isolating encapsulation changes, and disabling modifications and opening extensions are restrictions
  • The simple factory complies with the DRY principle and does not support the OCP principle.
  • The factory method mode fully supports the OCP principle and uses the inheritance mechanism.
  • Abstract Factory mode factory method mode fully supports the OCP Principle
  • The LSP principle is an important principle for OCP to become possible. The Abstract Factory mode and factory method mode fully comply with LSP.
  • Dependent on abstraction. A class derived from a specific class obviously violates the DIP principle.
  • GRASP is another design pattern system, which is similar to the GOF design pattern in many places. Understanding GRASP can help us think about it
     

Refer to: Summary of OO design principles, power of perspective-let's talk about OO design principles.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.