Advanced Java | viewing object-oriented as a whole

1, Object oriented

Object oriented is the core idea of Java programming. Its basic characteristics are inheritance, encapsulation and polymorphism.

1. Feature encapsulation

The structure, data and operation are encapsulated in the object entity. When using, you can not pay attention to the internal structure of the object and can only access the function entrance with open permissions, so as to reduce the degree of program coupling and provide security and sustainable maintenance.

public class Concept01 {
    public static void main(String[] args) {
        Student student = new Student("Zhang San","third year in high school",29f);
        student.conclusion();
    }
}
class Student {
    private String name ;
    private String grade ;
    private Float score ;
    public Student(String name, String grade, Float score) {
        this.name = name;
        this.grade = grade;
        this.score = score;
    }
    public void conclusion (){
        System.out.println("full name:"+this.getName());
        System.out.println("Grade:"+this.getGrade());
        System.out.println("fraction:"+this.getGrade());
        if (this.getScore() >= 100.0f){
            System.out.println("Comments: top student of this semester");
        } else {
            System.out.println("Comments: potential stocks this semester");
        }
    }
}

The case describes the Student's term summary, constructs the specific Student object through the construction method, and obtains the Student's term evaluation only through the conclusion method.

2. Inheritance of characteristics

In addition to providing its own capabilities, subclasses can also obtain the open properties and methods of the parent class through inheritance to enhance their own functions.

public class Concept02 {
    public static void main(String[] args) {
        // Judge whether Digital is the parent class of Phone
        System.out.println(Digital.class.isAssignableFrom(Phone.class));
    }
}
class Digital {}
class Phone extends Digital{}

Here, judge that Digital is the Phone parent class through the isAssignableFrom method.

3. Polymorphism of characteristics

Different main classes give different implementation methods for the same action. Polymorphism is also a common means for Java to describe design patterns. The most direct function is program decoupling.

public class Concept03 {
    public static void main(String[] args) {
        Animal animalDog = new Dog();
        Animal animalCat = new Cat();
        animalDog.voice();
        animalCat.voice();
    }
}
class Animal {
    public void voice () {
        System.out.println("Animal ... voice");
    }
}
class Dog extends Animal {
    @Override
    public void voice() {
        System.out.println("Dog ... Wang wang");
    }
}
class Cat extends Animal {
    @Override
    public void voice() {
        System.out.println("Cat ... Meow meow");
    }
}

Generally, animals have the ability to make sounds, but different animals have different sounds. Here, based on polymorphism, different animals have different sound characteristics.

2, Relationship map

After understanding object-oriented, you also need to understand the basic relationship model. In actual business, you solve scenario problems based on these basic relationships.

1. Inheritance and Implementation

Inheritance relationship: it emphasizes the inheritance of attributes and methods from parent class to child class. Implementation relationship: emphasize the logic of describing abstract and concrete implementation.

/**
 * inherit
 */
class classA {}
class classB extends classA {}
interface interfaceA {}
interface interfaceB extends interfaceA {}
/**
 * realization
 */
class classC implements interfaceA,interfaceB{}

2. Dependency and Association

Dependency relations: commonly used to describe methods, local variables or input parameters, that is, another class is called in the method of class. Association relationship: the member variable of a class is another class, such as the common one-to-one and one to many relationships.

/**
 * rely on
 */
class RelyA {}
class RelyB {
    public void depend (RelyA rely){}
}
/**
 * relation
 */
class AssociateA {}
class AssociateB {
    private AssociateA associateA ;
}

3. Combination and aggregation

Aggregation relationship: describes the relationship between the whole and the part, but the part does not need to depend on the whole. Combinatorial relationship: describes the relationship between the whole and the part, but the part needs to depend on the whole.

/**
 * polymerization
 */
class ElementA {}
class ElementB {}
class Aggregation {
    private ElementA elementA ;
    private ElementB elementB ;
}
/**
 * combination
 */
class PortionA{}
class PortionB{}
class Composition {
    private PortionA portionA ;
    private PortionB portionB ;
}

Three, mode and principle

In the face of complex business, you can often refer to design patterns and basic principles to design reasonable business structure and realize high cohesion and low coupling of code. However, in some specific scenarios, you should decisively break through these templates or principles to better support the business.

1. Design pattern

Create mode

The creation process of abstract object instantiation provides efficient management and reasonable creation means for different types of objects.

  • Singleton mode
  • Prototype mode
  • Factory mode
  • Builder pattern

Structural mode

The assembly mode of design class and reasonable object structure are conducive to supporting the continuous iteration of business, and the structure will directly affect the sustainable maintenance of code.

  • proxy pattern
  • Appearance mode
  • Adapter mode
  • Decorator mode
  • Combination mode
  • Sharing element mode
  • Bridge mode

Behavior pattern

The behavior pattern involves object responsibility definition, communication and cooperation, and the most specific business logic implementation, so as to clarify the process track when the program runs.

It can control the behavior and responsibilities of different classes based on inheritance or implementation, that is, the top-level abstract control behavior, and the lower level makes concrete logical implementation level by level; Or directly aggregate management responsibility objects for unified distribution.

  • Observer mode
  • template method
  • Strategy mode
  • Command mode
  • Mediator mode
  • Memo mode
  • Interpreter mode
  • Iterator mode
  • State mode
  • Responsibility chain model
  • Visitor mode

2. Basic principles

  • Principle of opening and closing: when designing the code structure, we should consider opening to extension and closing to modification, building the structure with abstract thinking and realizing the extension details.

  • Single responsibility: a class should be responsible for only one responsibility; Reduce large-scale program changes caused by one code change and reduce class complexity;

  • Interface isolation: each interface should be a role; Try to avoid the methods that cannot be used but must be implemented in the specific implementation class;

  • Dependency inversion: the upper module should not rely on the lower module, and the abstract logic should not rely on specific details, that is, the central idea is interface oriented programming.

  • Richter substitution: follow the Richter substitution principle when inheriting. Try not to override the methods of the parent class in the subclass, so as to expand the functions of the parent class;

  • Dimitri principle: the least known principle, that is, the less the class object knows about the class it depends on, the better, so as to reduce the degree of coupling;

  • Composition / aggregation reuse: new objects should use some existing objects to become components of new objects and realize the reuse of existing functions, so as to reduce the complexity of a single class.

4, Business application

In business development, many complex logics are designed and implemented based on the idea of object-oriented, but in fact, the business is constantly changing, so whether it is the commonly used Mvc mode or domain design, as long as it goes through multiple version iterations and multi person development, the final code will be fascinating at the logical level.

That is a common phenomenon: new people reconstruct and old people constantly repair problems. However, iron problems and water development. As everyone who has experienced reconstruction knows, the so-called large-scale reconstruction is difficult to completely solve problems, and even it is a circular action. Therefore, the business code is more reasonable in that version cycle. From a development perspective, it can also be understood as the author's personal perspective. The specific business development is usually considered from the following perspectives:

  • Normative constraints

This is the most important foundation in business engineering. No matter how complex the business is, it is inseparable from the corresponding data addition, deletion, modification and query. Therefore, do a good job in unified code style management for routine basic operations, which will help others quickly understand the overall structure and logic.

The style here refers to the unification of interface naming, parameters, components and middleware. Take the persistence layer as an example to avoid the mixing of multiple components. If it is a project with a relatively long cycle, it is often seen that there are many situations in the implementation logic of paging query alone.

  • Reusability

Variability is the characteristic of the business itself, so the highly reusable business code itself has great limitations. For example, many common methods continuously expand the parameters in order to adapt to various scenarios, and then some special services will also transfer special parameters.

Some developers often say that it can be implemented with one interface and absolutely do not use two interfaces. It seems very personalized. In fact, it has been on the road of digging a pit. Multiple functions request the same interface, which means that many logical adaptations must be considered for any interface change.

Therefore, from the top down, there is no need to over consider reuse. From the bottom up, there are relatively few changes at the bottom, so reuse should be considered.

  • Business stratification

From the perspective of project life cycle, business is an iterative process without excessive avant-garde design. No one knows how long the project life cycle is. The safest way is rapid iteration. Product and technical engineering can support business development quickly and stably.

Classic business hierarchical management is the basic support for rapid iteration. For example, the commonly used Mvc mode can refine management again in complex business scenarios or approach domain design.

  • Process segmentation

Business can be understood as process management. Small processes can usually be handled directly in the service, but complex processes pay great attention to design. A basic idea is segmented management. A classic case is placing an order: when the settlement page is built, the order is initialized - when the order is submitted - when the payment is successful, the order will be executed.

  • Details

Logical details should continue to be rigorous, business implementation means and ideas should be appropriately relaxed, the process can stand the test, the bottom layer can realize reasonable reuse, and the component selection should stand at a high latitude, which is basically enough.

5, Source code address

GitHub·address
https://github.com/cicadasmile/java-base-parent
GitEE·address
https://gitee.com/cicadasmile/java-base-parent

Reading labels

[Java Foundation][Design pattern][Structure and algorithm][Linux system][database]

[Distributed architecture][Microservices][Big data component][SpringBoot advanced][Spring & Boot Foundation]

[Data analysis][Technical map][ Workplace]

Keywords: Design Pattern Polymorphism encapsulation inheritance

Added by jswinkelman on Sat, 25 Dec 2021 17:25:02 +0200