(B) the principles of Java design patterns Design patterns

Before learning Java design patterns, it is necessary to understand the principles of design patterns.

Open Closed Principle

definition

  • A software entity, such as classes, modules and functions should be open for extension but closed for modification

  • Achieve the expansion frame abstract the details of construction, with
  • Benefits: improve software reusability and maintainability

Coding

Creating interfaces

public interface ICourse {
    Integer getId();

    String getName();

    Double getPrice();
}

Creating the implementation class

@ToString
@AllArgsConstructor
public class JavaCourse implements ICourse {

    @Getter
    private Integer id;

    @Getter
    private String name;

    @Getter
    private Double price;
}

Test category

public class Test {

    public static void main(String[] args) {
        ICourse iCourse = new JavaCourse(96, "我的Java课程", 348d);
        System.out.println("课程ID: " + iCourse.getId() + " 课程名称: " + iCourse.getName() + "课程价格: " + iCourse.getPrice());
    }
}

Console output

课程ID: 96 课程名称: 我的Java课程课程价格: 348.0

If you now want to sell at a discount program, in accordance with the principle of opening and closing to design, open for extension, but closed for modification.

Creating discount classes

public class JavaDiscountCourse extends JavaCourse {
    public JavaDiscountCourse(Integer id, String name, Double price) {
        super(id, name, price);
    }

    public Double getOriginPrice() {
        return super.getPrice();
    }

    @Override
    public Double getPrice() {
        return super.getPrice() * 0.8;
    }
}

Modify the application class

public class Test {

    public static void main(String[] args) {
        ICourse javaCourse = new JavaDiscountCourse(96, "我的Java课程", 348d);

        JavaDiscountCourse iCourse = (JavaDiscountCourse) javaCourse;
        System.out.println("课程ID: " + iCourse.getId() + " 课程名称: " + iCourse.getName() + "课程原价: " + iCourse.getOriginPrice() + " 课程折后价格: " + iCourse.getPrice());
    }
}

Console output

课程ID: 96 课程名称: 我的Java课程课程原价: 348.0 课程折后价格: 278.40000000000003

Here is a place to note, Double * 0.8floating point accuracy after output had lost the case, you can use BigDecimalthe Stringconstructor public BigDecimal(String val)to resolve.

modifyJavaDiscountCourse

public class JavaDiscountCourse extends JavaCourse {
    public JavaDiscountCourse(Integer id, String name, Double price) {
        super(id, name, price);
    }

    public Double getOriginPrice() {
        return super.getPrice();
    }

    @Override
    public Double getPrice() {
        return new BigDecimal(super.getPrice().toString()).multiply(new BigDecimal("0.8")).doubleValue();
    }
}

Console output

课程ID: 96 课程名称: 我的Java课程课程原价: 348.0 课程折后价格: 278.4

Dependency Inversion Principle

definition

  • High-level modules should not depend on low-level modules, both of which should rely on their abstract
  • Abstract should not rely on details; details should rely on abstract
  • An interface for programming, not for the realization of programming
  • May reduce the risk of the coupling between classes, improve system stability, improve code readability and maintainability, reduce modify the program caused by: Advantages

Coding

Counterexample

Create a class

public class Geely {
    public void studyJavaCourse() {
        System.out.println("Geely在学习Java课程");
    }

    public void studyFECourse() {
        System.out.println("Geely在学习FE课程");
    }

    public void studyPythonCourse() {
        System.out.println("Geely在学习Python课程");
    }
}

Test category

public class Test {
    // v1
    public static void main(String[] args) {
        Geely geely = new Geely();
        geely.studyFECourse();
        geely.studyJavaCourse();
    }
}

Console output

Geely在学习FE课程
Geely在学习Java课程

At this time, if we want to learn Ruby Geely course, we can only Geelyadd class

public void studyRubyCourse() {
    System.out.println("Geely在学习Ruby课程");
}

Then, in the Test class

geely.studyRubyCourse();

{% note warning %}

Does not meet the Dependency Inversion Principle

{% endnote %}

Positive example

Creating interfaces

public interface ICourse {
    void studyCourse();
}

Create a class with a member variableICourse course

@AllArgsConstructor
public class Geely {

    @Setter
    private ICourse course;

    public void studyImoocCourse() {
        course.studyCourse();
    }

}

Creating the implementation class

public class FECourse implements ICourse {
    @Override
    public void studyCourse() {
        System.out.println("Geely在学习FE课程");
    }
}
public class JavaCourse implements ICourse {
    @Override
    public void studyCourse() {
        System.out.println("Geely在学习Java课程");
    }
}
public class PythonCourse implements ICourse {
    @Override
    public void studyCourse() {
        System.out.println("Geely在学习Python课程");
    }
}

Test category

public class Test {
    public static void main(String[] args) {
        Geely geely = new Geely(new JavaCourse());
        geely.studyImoocCourse();

        geely.setCourse(new FECourse());
        geely.studyImoocCourse();
    }
}

Console output

Geely在学习Java课程
Geely在学习FE课程

As a result, if you want to add a new course, you can just create the implementation class. Then set the application class implementation class, without changing other code, in line with the principle of dependency inversion.

Single Responsibility Principle

definition

  • The reason there is not more than one class leads to change
  • A class / interface / method is only responsible for a duty
  • Benefits: reduce the complexity of the class, the class improve readability, increase maintainability of the system, reducing the risk caused by changes

Coding

Counterexample

Create a class

public class Bird {
    public void mainMoveMode(String birdName) {
        System.out.println(birdName + " 用翅膀飞");
    }
}

Test category

public class Test {

    public static void main(String[] args) {
        Bird bird = new Bird();
        bird.mainMoveMode("大雁");
        bird.mainMoveMode("鸵鸟");
    }
}

Console output

大雁 用翅膀飞
鸵鸟 用翅膀飞

Ostrich feet away, so we changed the Bird class

public class Bird {
    public void mainMoveMode(String birdName) {
        if ("鸵鸟".equals(birdName)) {
            System.out.println(birdName + " 用脚走");
        } else {
            System.out.println(birdName + " 用翅膀飞");
        }
    }
}

If there are more birds, more else we need to write code.

Positive example

We modified example of counter-examples under

public class FlyBird {
    public void mainMoveMode(String birdName) {
        System.out.println(birdName + " 用翅膀飞");
    }
}
public class WalkBird {
    public void mainMoveMode(String birdName) {
        System.out.println(birdName + " 用脚走");
    }
}

Add the test class

public class Test {

    public static void main(String[] args) {
        FlyBird flyBird = new FlyBird();
        flyBird.mainMoveMode("大雁");

        WalkBird walkBird = new WalkBird();
        walkBird.mainMoveMode("鸵鸟");
    }
}

Console output

大雁 用翅膀飞
鸵鸟 用脚走

As another example

Creating interfaces

/**
 * 课程内容
 *
 * @author gaochen
 * Created on 2019/7/27.
 */
public interface ICourseContent {

    String getCoursName();

    byte[] getCourseVideo();

}
/**
 * 课程管理
 *
 * @author gaochen
 * Created on 2019/7/27.
 */
public interface ICourseManager {
    void studyCourse();

    void refundCourse();
}

Create an implementation class, course content and course management has two functions

public class CourseImpl implements ICourseContent, ICourseManager {
    @Override
    public String getCoursName() {
        return null;
    }

    @Override
    public byte[] getCourseVideo() {
        return new byte[0];
    }

    @Override
    public void studyCourse() {

    }

    @Override
    public void refundCourse() {

    }
}

Interface Segregation Principle

definition

  • A plurality of dedicated interfaces, rather than using a single interface to the total, the client should not rely on it does not interface
  • A class of a class should be dependent on the establishment of a minimum interface
  • The establishment of a single interface, do not create bloated interface
  • Interface possible refinement process to minimize interface
  • Pros: We often say that in line with the design of high cohesion and low coupling, so that the class has good readability, scalability and maintainability.

{% note warning %}

Note that the principle of proportionality, must be appropriate

{% endnote %}

Coding

Counterexample

Creating interfaces

public interface IAnimalAction {

    void eat();

    void fly();

    void swim();
}

Creating the implementation class

public class Bird implements IAnimalAction {
    @Override
    public void eat() {
        System.out.println("鸟 吃饭");
    }

    @Override
    public void fly() {
        System.out.println("鸟 飞");
    }

    @Override
    public void swim() {
        // 鸟不会游泳,空实现
    }
}
public class Dog implements IAnimalAction {
    @Override
    public void eat() {
        System.out.println("狗 吃饭");
    }

    @Override
    public void fly() {
        // 狗不会飞,空实现
    }

    @Override
    public void swim() {
        System.out.println("狗 游泳");
    }
}

We can see that the bird and the dog realizes an interface, each has a useless interface, the interface isolation in violation of the principles, can only take the form of an empty implementation. But for consumers, it can still call the dog fly method to obtain the realization of space.

Positive example

The reaction of Example Interface Interface split into three separate interfaces

public interface IEatAnimalAction {
    void eat();
}
public interface IFlyAnimalAction {
    void fly();
}
public interface ISwimAnimalAction {
    void swim();
}

DogChanged

public class Dog implements IEatAnimalAction,ISwimAnimalAction {
    @Override
    public void eat() {
        System.out.println("狗 吃饭");
    }

    @Override
    public void swim() {
        System.out.println("狗 游泳");
    }
}

BirdChanged

public class Bird implements IEatAnimalAction,IFlyAnimalAction {
    @Override
    public void eat() {
        System.out.println("鸟 吃饭");
    }

    @Override
    public void fly() {
        System.out.println("鸟 飞");
    }
}

This will be a big success interface optimized for a shared responsibility of small interface implementation class can implement multiple interfaces functions as needed.

Dmitry principle

definition

  • An object should be kept to a minimum understanding of other objects. Also known as the principle of least know
  • Minimize the coupling between a class and class
  • Advantages: reducing the coupling between classes

Coding

Counterexample

Create a class curriculum

public class Course {
}

Create a project manager class

public class TeamLeader {

    public void checkNumberOfCourse(List<Course> courseList) {
        System.out.println("在线课程的数量是 :" + courseList.size());
    }
}

Creating boss class

public class Boss {

    public void commandCheckNumber(TeamLeader teamLeader) {
        List<Course> courseList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            courseList.add(new Course());
        }
        teamLeader.checkNumberOfCourse(courseList);
    }
}

Test category

在线课程的数量是 :20

We have a closer look, in fact, the boss does not need to know the details of the course, the project manager need only ask, how many courses, the project manager has to tell the boss section 20 online courses. The courses listed instead of the boss, project manager statistics.

We look UML class diagram

Positive example

The project manager for the modified class

public class TeamLeader {
    
    public void checkNumberOfCourse() {
        List<Course> courseList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            courseList.add(new Course());
        }
        System.out.println("在线课程的数量是 :" + courseList.size());
    }
}

The boss class

public class Boss {

    public void commandCheckNumber(TeamLeader teamLeader) {
        teamLeader.checkNumberOfCourse();
    }
}

This time it runs, the same results. But from the point of view UML class diagram, there is a lot of optimization.

Guess you like

Origin www.cnblogs.com/gcdd/p/12292118.html