Object-oriented design principles (JAVA)

Source: Internet
Author: User

One, single responsibility principle (Single Responsibility PRINCIPE,SRP )

1.1 Single Dutydefinition of the principle1) Definition: In a software system, a class is responsible only for the corresponding functions in a functional area. 2) Another way to define this is as follows: For a class, there should be only one cause for it to change.1.2packaging principles for variabilityThe more responsibilities a class (or large-to-module, small-to-method) assumes, the less likely it is to be reused. And if a class takes on too much responsibility, it is tantamount to coupling those responsibilities together, and when one of those responsibilities changes, it may affect the operation of other responsibilities. The duties of a class are mainly covered by two aspects: data responsibility and behavior responsibility, data responsibility is embodied by its attribute, and behavior responsibility is embodied by its method. Single responsibility principle is to achieve high cohesion, low-coupling guidelines, in many code refactoring techniques can find its existence, it is the simplest and most difficult to apply the principle, need to find the different responsibilities of the class and separation, and found that the multiple responsibilities of the class needs designers have strong analytical design capabilities and related refactoring experience.Ii. Opening and closing principle (open-closed PRINCIPLE,OCP)2. 1 definition of Open/Closed principle      A software entity should be open to extensions and closed for modifications. In other words, when designing a module, it should be allowed to be extended without modification, that is, to change the behavior of the module without modifying the source code.      2.2 Opening and closing principle Analysis       In the definition of open and closed principle, a software entity can refer to a software module, a local structure consisting of multiple classes, or a separate class.      Abstraction is the key to the open and closed principle. Most of the design modules are in accordance with the open and closed principle, in the evaluation of the merits and demerits of each model will be an important evaluation basis for the open and close principle, in order to determine whether the system based on this model has a good flexibility and scalability.third, the principle of substitution of the Richter scale (Liskov Substitution principle,lsp) 3.1 Richter substitution principle definition      1) If each object of type S is O1, there is an object O2 of type T, so that all program P defined in T is changed to O2 for all objects O1, and the behavior of the program P does not change, then the type S is a subclass of type T. 2) All references to the base class (parent class) must be able to use the object of its subclass transparently.3.2 The principle of substitution of Richter scale      The principle of substitution of the Richter scale can be expressed as follows: if the base class object can be used in the software, its subclass object must be used.      Replace the base class with its subclasses, the program will not produce any errors and exceptions, and conversely, if a software entity uses a subclass, then it is not necessarily able to use the base class. The principle of substitution of the Richter scale is one of the important ways to realize the open and closed principle, because the subclass object can be used wherever the base class object is used, so as far as possible the base class type is used in the program to define the object, while at run time the subclass type is determined, and the child class object is substituted for the parent class object.Four,Dependency Reversal Principle(dependenceinversion principle, DIP)4.1ConceptDependency Reversal Principleis to rely on abstraction, not to rely on implementation. (Abstractionsshould not depend upon details.) Details should depend uponabstractions.) to program for the interface, do not program for implementation. (Program to Aninterface, not an implementation.) that is, you should use interfaces and abstract classes for variable type declarations, parameter type declarations, method return type descriptions, and conversion of data types. Instead of using specific classes for variable type declarations, parameter type declarations, method return type descriptions, conversion of data types, and so on. To ensure that this is done, a concrete class should implement only the methods that are declared in the interface and the abstract class, not the redundant methods. The traditional process system design method tends to make the high-level module depend on the lower layer module, the abstraction level relies on the concrete level. The reversal principle is to reverse the false dependency. The important principle of object-oriented design is to create abstractions, and to materialize from abstract, materialized to give different implementations. An inheritance relationship is an export from abstraction to materialization. The abstraction layer contains the business logic of the application system and the macro-strategic decision which is important to the whole system, which is the embodiment of inevitability. The specific level contains some minor implementation-related algorithms and logic, as well as tactical decisions, with considerable contingency choices. Specific levels of code are constantly changing and cannot avoid errors. From the perspective of reuse, high-level modules should be reused, and is the focus of reuse, because it contains an application system the most important macro business logic, is more stable. In the traditional process design, reuse is focused on the reuse of the concrete level module. The principle of dependency reversal is the "inversion" of the traditional process design method, which is an effective specification for high-level module reuse and maintainability. Exception: Object creation is a violation of the "open-closed" principle and the dependency reversal principle, but through the factory model, it can be a good solution to the object creation process of dependency reversal problem.4.2RelationshipThe principle of "open-close" and dependence reversal is the relationship between the goal and the means. If the principle of opening is the goal, reliance on the reversal principle is the means to reach the "open and close" principle. If the best "open and close" principle is to be achieved, it is necessary to obey the principle of dependency reversal and the principle of dependence reversal is the best norm of "abstraction". The principle of substitution on the Richter scale is based on the reversal principle, which is an important supplement to the principle of the substitution of the Richter.4.3type of coupling (or dependency) relationship:0 coupling (nilcoupling) Relationship: Two classes do not have a coupling relationship specific coupling (concretecoupling) Relationship: Occurs between two specific (instantiated) classes, caused by a class to a direct reference to another specific class. Abstract coupling (abstractcoupling) Relationship: Occurs between a concrete class and an abstract class (or interface), allowing for maximum flexibility between the two classes that must have a relationship.Five, interface isolationprinciples (Interface segregation Principle,isp)5.1 Interface Isolation principle definition      1) The client should not rely on interfaces that it does not need 2) once an interface is too large, it needs to be split into smaller interfaces, and clients using that interface need only know the methods associated with them.5.2 Interface Isolation principle Analysis      The principle of interface isolation refers to the use of multiple specialized interfaces rather than a single total interface.         Each interface should assume a relatively independent role, not a lot, do not do the things that should be done to do.         (1) An interface represents only one role, and each role has its own specific interface, and this principle can be called the "role isolation principle". (2) The interface simply provides the behavior required by the client.       That is, the required method, the client does not need the behavior is hidden, should provide the client with the smallest possible separate interface, rather than provide a large total interface.       When you split an interface using the interface isolation principle, you must first meet a single principle of responsibility, define a set of related operations in an interface, and, with high cohesion, the fewer methods in the interface are as good as possible. Can be used in the design of the system in a customized way, that is, for different clients to provide a wide range of interfaces, only the user needs to provide the behavior, and hide the user does not need the behavior.vi. Synthesis/Aggregation multiplexing principle (Composite/aggregatereuseprincipleorCARP)6.1ConceptDefinition: Use some existing objects inside a new object to make them part of the new object, and the new objects are used to reuse the objects by delegating them to them. The synthesis/aggregation should be used first, and the synthesis/aggregation makes the system flexible, followed by the inheritance to achieve the purpose of reuse. When using inheritance, we should strictly follow the principle of the Richter substitution. Effective use of inheritance can help to understand problems, reduce complexity, and misuse of inheritance can increase system build-up, maintenance difficulties, and system complexity. If the two classes are "has-a" the relationship should use the composition, aggregation, and if the "is-a" relationship can use inheritance. "Is-a" is defined in strict taxonomic sense, meaning that one class is the "one" of another. and "Has-a" is different, it means that a role has a certain responsibility.6.2What is synthesis? What is aggregation? Synthesis (composition) and aggregation (Aggregation) are a special kind of association (association). aggregations represent the whole and part of the relationship, which means "owning". such as Mercedes-Benz S360 car, the relationship between Mercedes-Benz S360 engine, Mercedes-Benz S360 tires is an aggregation relationship, leaving the Mercedes-Benz S360 car, engine, tires lost the meaning of existence. In design, aggregation should not occur frequently, which increases the coupling of the design. Synthesis is a stronger "own", part-and-whole life cycle. The new objects of the composition completely dominate their constituent parts, including their creation and annihilation.   A composition object of a composition relationship cannot be shared with another composition relationship. In other words, a composition is an aggregation of values (Aggregation byvalue), whereas a general aggregation is a referenced aggregation (Aggregation byreference). Understand the composition and aggregation relationships, and then to understand the composition/aggregation principle should be clear, to avoid in the system design, the inheritance level of a class more than 3 layers, you need to consider refactoring code, or redesign the structure. The best approach, of course, is to consider the use of synthetic/aggregation principles.6.3by Crafting/advantages and disadvantages of aggregationAdvantages:1) The only way to access an ingredient object from a new object is through the interface of the Component object. 2) This reuse is a black-box reuse because the inner details of the constituent objects are invisible to the new object. 3) This multiplexing supports packaging. 4) This multiplexing requires less reliance. 5) Each new class can focus on one task. 6) This multiplexing can be performed dynamically during runtime, and new objects can dynamically reference objects of the same type as the constituent objects. 7) As a means of reuse can be applied to almost any environment.Disadvantages:Is that there will be more objects in the system to be managed.6.4advantages and disadvantages of reuse through inheritanceAdvantages:The new implementation is easier because most of the functionality of the superclass can be automatically entered into subclasses through inherited relationships. It is easier to modify and extend inherited implementations.Disadvantages: Inheritance reuse destroys wrappers, because inheritance exposes the implementation details of a superclass to subclasses. Because the inner details of the superclass are often transparent to the subclass, this reuse is transparent multiplexing, also known as "white box" multiplexing. If the superclass changes, then the implementation of the subclass has to change. Implementations inherited from the superclass are static and cannot be changed within the runtime, without sufficient flexibility. Inheritance can only be used in a limited environment.Seven,Dimitri Law (lawof Demeter,LoD)7.1 Dimitri Law definition Definition: A software entity should interact with as few interactions as possible with other entities. This way, when a module is modified, it will affect the other modules as little as possible.   Scaling is relatively easy. This is a limitation of communication between software entities. It requires limiting the width and depth of communication between software entities.7.2Other expressions of the Dimitri Law:1) only communicate with your direct friends. 2) Don't talk to "strangers". 3) Each software unit has only minimal knowledge of the other units, and is limited to the software units that are closely related to the unit.7.3the Dimitri rule of the narrow senseIf two classes do not have to communicate directly with each other, then these two classes should not have a direct interaction. If one of the classes needs to invoke a method of another class, the call can be forwarded through a third party. The determination of the circle of Friends "friend" condition: 1) The current object itself (this) 2) is passed in as a parameter to the object in the current object Method 3) An instance variable of the current object directly refers to an object 4) An instance variable of the current object if it is a cluster, So the elements in the gathering are all friends. 5) Any object that is created by the current object, if one of the above conditions is met, is the "friend" of the current object, or "stranger". Cons: There will be a lot of small methods in the system, scattered in all corners of the system. Complementary to the dependency reversal principle7.4The shortcomings of the narrow Dimitri Law:A large number of small methods are created in the system, and these methods simply transmit indirect calls, regardless of the business logic of the system. Following the Dimitri rule between classes is a simplification of the local design of a system, since each part is not directly associated with objects of long distance. However, this also causes the communication efficiency between different modules of the system to be reduced, and the system can not be easily coordinated between the different modules.7.5 Generalized rules of DimitriIt refers to the control of information flow, flow direction and the influence of information, mainly on the control of information hiding. The concealment of information can decouple the subsystems, allowing them to be independently developed, optimized, used, and modified, while facilitating the reuse of the software, since each module is independent of other modules, so each module can be used independently of other locations.  The larger the size of a system, the more important it is to conceal information, and the greater the importance of information hiding. Excerpt from: http://www.cnblogs.com/hulitut/archive/2012/03/22/2412668.html

Object-oriented design principles (JAVA)

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.