First, object-oriented

Object-oriented is the most core idea in Java programming, the basic characteristics: inheritance, encapsulation, polymorphism.

1. Encapsulation of features

Encapsulate the structure, data and operation in the object entity, which can be used without paying attention to the internal structure of the object and can only access the function entrance with open permissions, thus reducing the coupling degree of the program and providing security and sustainable maintenance.

public class Concept01 {
    public static void main(String[] args) {
        Student student = new Student("Zhang"."Three high".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 (a){
        System.out.println("Name:"+this.getName());
        System.out.println("Grade:"+this.getGrade());
        System.out.println("Score:"+this.getGrade());
        if (this.getScore() >= 100.0 f){
            System.out.println("Comments: Top student of this term.");
        } else {
            System.out.println("Comments: Potential stock for this semester"); }}}Copy the code

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

2. Inheritance of characteristics

In addition to providing its own capabilities, a subclass can also acquire attributes and methods opened by its parent class through inheritance to enhance its own capabilities.

public class Concept02 {
    public static void main(String[] args) {
        // Determine that Digital is the Phone parentSystem.out.println(Digital.class.isAssignableFrom(Phone.class)); }}class Digital {}
class Phone extends Digital{}
Copy the code

The isAssignableFrom method determines that Digital is the Phone parent.

3. Polymorphism of features

Different principal classes give different ways to implement the same action. Polymorphism is also a common way to describe design patterns in Java. The most direct effect is program decoupling.

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

Usually animals have the ability to make sounds, but different animals make different sounds, and this is based on polymorphic implementation, different animal vocal characteristics.

2. Relationship map

Once you understand object orientation, you also need to understand the basic relationship models that are used to solve scenario problems in real business.

1. Inheritance and implementation

Inheritance: Emphasizes the inheritance of attributes and methods from parent to subclass. Implementation relationships: Emphasize the logic that describes abstract and concrete implementations.

/** * inherits */
class classA {}
class classB extends classA {}
interface interfaceA {}
interface interfaceB extends interfaceA {}
/** * implements */
class classC implements interfaceA.interfaceB{}
Copy the code

2. Dependency and association

Dependencies: Used to describe a method local variable or input parameter, that is, a method of a class that calls another class. Association: The member variable of a class is another class, such as the common one-to-one, one-to-many relationship.

/** * depends on */
class RelyA {}
class RelyB {
    public void depend (RelyA rely){}}/** * associated with */
class AssociateA {}
class AssociateB {
    private AssociateA associateA ;
}
Copy the code

3. Combination and polymerization

Aggregate relationship: Describes the relationship between the whole and the parts, but the parts need not depend on the existence of the whole. Combinatorial relationship: Describes the relationship between the whole and the parts, but the parts depend on the whole to exist.

/** ** aggregate */
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 ;
}
Copy the code

Mode and principle

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

1. Design patterns

Create a model

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

  • The singleton pattern
  • The prototype pattern
  • The factory pattern
  • Builder model

Structure mode

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

  • The proxy pattern
  • The appearance model
  • Adapter mode
  • Decorator pattern
  • Portfolio model
  • The flyweight pattern
  • Bridge pattern

Behavior patterns

Behavior patterns involve the definition of object responsibilities, communication collaboration, and most specifically the implementation of business logic, specifying the process trajectory of the program as it runs.

Different types of behavioral responsibilities can be controlled based on inheritance or implementation, that is, the top layer of abstract control behavior, the lower layer of concrete logic implementation step by step; Or directly aggregate the objects of management responsibility and make unified allocation.

  • Observer model
  • Template method pattern
  • The strategy pattern
  • Command mode
  • Mediator model
  • Memo mode
  • Interpreter mode
  • Iterator pattern
  • The state pattern
  • Chain of Responsibility model
  • Visitor pattern

2. Basic principles

  • Open and close principle: when designing code structure, we should consider open to extension and close to modification, build structure with abstract thinking and implement extension details concretely.

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

  • Interface isolation: Each interface should be a role; Try to avoid methods that are not used in concrete implementation classes but must be implemented.

  • Dependency inversion: upper-level modules should not depend on lower-level modules, and abstract logic should not depend on details, i.e. the central idea is interface oriented programming.

  • Richter’s substitution: Inherit according to the Richter’s substitution principle, try not to rewrite the method of the parent class in the subclass, can extend the function of the parent class;

  • Demeter principle: the least known principle means that the class object knows as little as possible about the class it depends on, so as to reduce the coupling degree;

  • Composite/aggregate reuse: The new object should use part of the existing object to make it part of the new object to reuse the existing function, thus reducing the complexity of a single class.

Fourth, business application

In business development, a lot of complex logic are based on the idea of object-oriented design and implementation, but in fact business is constantly changing, so whether the commonly used Mvc pattern, or areas of design, as long as after multiple versions iteration, many people participate in the development, at the end of the code in the logical level would be fascinating.

It is also a phenomenon that is often said: the new person reconstructs, the old person fixes the problem continuously, but the problem of iron, the development of flow, all the students who have experienced the reconstruction know that the so-called large-scale reconstruction is difficult to solve the problem completely, and even it is a circular action. So the business code is more in that version cycle is reasonable, standing in a development perspective, here can also be understood as the author’s personal perspective, usually from the following perspectives to think about specific business development:

  • discipline

I think this is the most important foundation in business engineering. No matter how complex the business is, it is inseparable from the corresponding data increase, deletion, change and check. Therefore, unified code style management for routine basic operations can help others to quickly understand the overall structure and logic.

The style here refers to the unification of interface naming, parameters, components, middleware, etc. Taking persistence layer as an example, it avoids the mixing of multiple components. If it is a project with a relatively long cycle, it is often seen that the implementation logic of single paging query has various situations.

  • reusability

Variability is the characteristic of the business itself, so the highly reusable business code itself has great limitations. For example, many common methods, to adapt to various scenarios, continue to expand the parameter, and then some special services will also carry out special parameter transmission.

There are some development often said, can use an interface to achieve, absolutely do not use two interfaces, seems to have a personality, actually has walked on the road to dig a hole, multiple functions request the same interface, that means any interface changes have to consider a lot of logical adaptation.

So from the top down, you don’t have to think too much about reuse, and from the bottom up, you have to think too little about reuse.

  • The business layer

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

Classic hierarchical business management is the basic support for rapid iteration, such as the commonly used Mvc pattern, which can be refined again in complex business scenarios, or closer to the domain design.

  • Process section

Business can be understood as process management. Small processes can usually be handled directly in service, but complex processes are very particular about design. A basic idea is segmentalized management.

  • The details

Logical details should continue to pursue rigorous, business implementation means and ideas appropriate relaxation, the process can withstand the test, the underlying implementation of reasonable reuse, component selection should stand in the high latitude, it is basically enough.

Five, source code address

Making address GitEE, https://github.com/cicadasmile/java-base-parent, https://gitee.com/cicadasmile/java-base-parentCopy the code