java programming principles Know

Seven principles of program design

First, the principle of opening and closing

We designed for function modules open for extension, but closed for modification: the use of the interface (abstract) programming (multi-state properties), for the realization of the function expansion needs at the same time, not allowed to change the original code. Improve object reusability, maintainability, flexibility.

Abstract says, we want to build solid objects created with abstract thinking, with the specific implementation details to the extended entity object implementation.

Specifically, the functional business requirements can go to expansion, but the functionality has been achieved should not go to modify.

  • Requirements: a simple factory pattern and factory method pattern to understand the opening and closing principle .

  • analysis:

    1. Factory pattern is to get an instance of an object model builders, we do not care how the object is generated, only care about the results.

    2. Simple factory pattern is facing a relatively simple business scenarios, for acquiring an object instance. We need to pass parameters related businesses, so a simple factory object to do the appropriate judgment, and then returned to us corresponding instance object. The factory object to do a lot of things, he violates the single responsibility principle , when we need to expand the business when the factory object must be to modify, add business judgment, returns the corresponding new instance of an object. This is contrary to the principle of opening and closing .

      public class FruitsFactory {
      
          /**
           * @description: 
           * @param fruitsName
           * @return com.lmc.gp13280.pattern.factory.fruits.IFruits
           * @date 2019/5/23 15:44
           * @author lmc
           */
          public IFruits product(String fruitsName){
      
              if(null != fruitsName && fruitsName != ""){
                  System.out.println("客户需求的水果是"+fruitsName);
                  if("苹果".equals(fruitsName)){
                      System.out.println("水果工厂生产了苹果");
                      return new Apple();
                  }
                  if("橙子".equals(fruitsName)){
                      System.out.println("水果工厂生产了橙子");
                      return new Orange();
                  }
                  if("香蕉".equals(fruitsName)){
                      System.out.println("水果工厂生产了香蕉");
                      return new Banana();
                  }
                  return null;
              }else{
                  return null;
              }
          }
      }

      The above is a fruit factory, if I want to strawberries, it is necessary to modify the code to achieve the production of strawberries.

    3. The method of the abstract factory pattern is a factory interface that allows specific instances of subclasses factory object implements the factory interface. We want a specific instance of an object, only to find the corresponding sub-class factory implementation class on it, if need business expansion, we do not need to modify the original factory subclass only need to add a new sub-class factory on the line. This enables business expansion, but does not modify the original program logic. Follow the on-off principle and the principle of single responsibility .

      public interface IFruitsFactory {
          /**
           * 工厂的生产方法
           * @return IFruits
           */
          IFruits product();
      
      }
      public class AppleFactory implements IFruitsFactory {
          @Override
          public IFruits product() {
      
              System.out.println("苹果工厂只生产苹果");
              return new Apple();
          }
      }
      public class BananaFactory implements IFruitsFactory {
          @Override
          public IFruits product() {
              System.out.println("香蕉工厂只生产香蕉");
              return new Banana();
          }
      }
      public class OrangeFactory implements IFruitsFactory {
          @Override
          public IFruits product() {
              System.out.println("橙子工厂只生产橙子");
              return new Orange();
          }
      }

      The sample code above, we want to add specific fruit plants to expand their businesses, only need to add the corresponding sub-class to implement the interface plant fruit plants on the line.

    4. Achieve business expansion, does not change the original program is to follow the principle of opening and closing.

Second, the Dependency Inversion Principle

spring dependency injection that everyone is familiar, in fact, is the Dependency Inversion Principle program objects depend on other objects, it should rely on their abstract, do not rely on implementation, should rely on top-level object, do not rely on a specific underlying objects. Because the concrete realization of the program is to achieve the implementation class, but we're going to rely on the top-level interface object implementation class, which is upside down, which is the dependency inversion.

Dependency Inversion principle is the core of a multi-state operation, the program at compile time, not to instantiate subclasses of objects, the virtual machine will go to select examples of specific sub-class objects when the program is running.

In programming, the general interface definition Well, it will not easily change. Because, in a mature system, change the interface, the design is equivalent to the overthrow of the reconstruction, and you are willing to do such a thing? However the implementation class, it may be modified slightly, or say change, add a new implementation class to replace. If you rely on its implementation class, as long as the implementation class changes, then the programmer's disaster is not coming in? If you rely on its top-level interface to the rest of us rely on the code of this interface do not need to do any changes, because the interface has not changed ah, only changes to the specific needs of business logic, or new business sub-class that implements the interface. It is not possible off work early .

By relying inversion can reduce the coupling between the class and class, and improve system stability, improve code
readability and maintainability, and can reduce the risks caused by modifying the program.

/**
 * 水果店 
 * @author: maocheng.liao
 * @create: 2020-02-23 15:20
 */
public class FruitShop {

    private IFruitsFactory fruitsFactory;

    public IFruitsFactory getFruitsFactory() {
        return fruitsFactory;
    }

    public void setFruitsFactory(IFruitsFactory fruitsFactory) {
        this.fruitsFactory = fruitsFactory;
    }
    /**
     * @description:
     * @param :从水果生产基地去进货水果
     * @return com.lmc.gp13280.pattern.factory.fruits.IFruits
     * @date 2020/2/23 15:34
     * @author maocheng.liao
     */
    public IFruits getFruits(){
        IFruits fruits = fruitsFactory.product();
        return fruits;
    }
}
/**
 * 水果店依赖倒置测试
 *
 * @author: maocheng.liao
 * @create: 2020-02-23 15:25
 */
public class FruitShopTest {
    public static void main(String[] args) {

        IFruitsFactory fruitsFactory= new AppleFactory();
        FruitShop fruitShop=new FruitShop();
        fruitShop.setFruitsFactory(fruitsFactory);
        IFruits apple = fruitShop.getFruits();
        apple.getName();

        fruitsFactory = new BananaFactory();
        fruitShop.setFruitsFactory(fruitsFactory);
        IFruits banana = fruitShop.getFruits();
        banana.getName();

        fruitsFactory = new OrangeFactory();
        fruitShop.setFruitsFactory(fruitsFactory);
        IFruits orange = fruitShop.getFruits();
        orange.getName();
    }
}

The code above is the simplest implementation dependent inversion, we relied on fruit and fruit factory interface interfaces, fruit shop in fruit production base to purchase fruit, as to what to purchase fruit, depending on what fruit production base in the production of fruit and fruit shop I want to go what fruits. Rather than relying on specific factory implementation class fruit and fruit concrete implementation class.

  • Note: Some simple code did not show, detailed code, see blog address: https: //www.cnblogs.com/programmerkaixin/p/10918844.html

Third, the Single Responsibility Principle

I think the single responsibility is Demeter a reflection of.

Single Responsibility Principle: See the name to know Italy, specializing in hand to do, do not nosy. For classes, interfaces, methods, only one in charge of their duties. After their responsibilities for program changes will not affect the responsibilities of its program. High cohesion, low coupling procedures must follow the single responsibility, clear division of labor, readability, maintainability.

The simplest example: we can not replace human hands eyes, the eyes can not be replaced hands and feet.

Bloated word is not well reflect the principle of single responsibility it? The code is written so bloated, it can not be a good play.

Fourth, the interface segregation principle

I think the interface segregation principle is the single responsibility principle a reflection, but also a reflection of Demeter.

Object-oriented programming, all things are objects.

Interface Segregation Principle: define more refinement and a clear division of specialized interfaces, not to define a single bloated interface. For the bloated interface, we not specific implementation, this would certainly be contrary to the principle of single responsibility .

The simplest example: a family car for objects, to large, said he belongs to the class of vehicles, he belongs to the car category, it belongs to the class of car. To small that it belongs to the family car category, private car class.

V. Demeter

Demeter also known as the principle of the least known, but also the taste of single responsibility principle and the interface isolation .

Demeter: low coupling, how to achieve the ultimate do, and that is dependent only on their true relationship of objects. Objects outside my mandate all turned away.

I think this is nothing to say, so that the single responsibility, Demeter well achieve it.

Sixth, Richter substitution principle

The official definition: where any base class (parent class) can occur, certain subclasses can occur. Substitution principle Richter inherited cornerstone multiplexed only when the derived class can replace the base class, the software unit of functionality is not affected, the base class can really be reused, derived class can also be increased on the basis of the base class on the new behavior. When an instance of a subclass should be able to replace any instance of its superclass, it is-A having a relationship between them.

I understand: Richter substitution principle in order to constrain the spread of inheritance, that is, in object-oriented programming, it must have a relationship to the is-A to use inheritance, but can not go in order to achieve certain business needs, in order to facilitate the use of inheritance and inheritance.

Precondition: Before each method call, the method should check the correctness of the arguments passed, only the right to perform the method, or that the caller breach of contract, not executed. This is known as pre-conditions ( Pre-condition).

Post Conditions: Once the precondition verification process must be performed, and the execution result must be ensured in line with the contract, which is called postconditions ( Post-condition). That is in line with the return value.

Alternatively Richter principle constraints: when there is inheritance, the subclass method of preconditions must be the same precondition superclass method covered or looser; and postconditions subclass method must the method of the same superclass covered postcondition or more stringent .

Not to inheritance and succession, but really have the time to inheritance to inherit.

Seven, synthetic multiplexing principle

Herein incorporated Dependency Inversion Principle synthetic multiplexing principle better effect .

Combination (has-a): analog computer assembly, memory, hard drives, cpucomposition, computer graphics ?????? between them, but there is no relationship between them. This is a combination of relationship, the same life cycle.

Polymerization contanis-a( ): Analogue employees aggregated into sectors. Employees and departments are independent of each other, one or two employee turnover does not affect the department object. Department dissolution does not affect the employee object.

Synthesis of multiplexing principles: multiplexing the program to make use of a combination of relationships, the relationship between the polymerization. Minimize the use of inheritance to achieve business needs.

All of the inheritance will be exposed to all subclasses. Break encapsulation, changing the class parent class, it will affect the subclass. High coupling.

Combination, the polymerization can well follow the Dependency Inversion Principle, the principle of opening and closing. Details of the implementation of the object member (a combination of the polymerization object) for a new object is hidden.

Synthesis of multiplexing with the principle of dependency inversion principle, the principle of good follow the opening and closing. Reach program availability, highly dimensional, high-readable.

Why spring so cattle? Why spring dependency injection? Why spring is lightweight?

Guess you like

Origin www.cnblogs.com/programmerkaixin/p/12350704.html