Six design principles of software engineering summary, case presentations

This article Source: GitHub · Click here || GitEE · Click here

A single responsibility principle

1, concept description

For classes, that a class should only be responsible for a duty. If a class is responsible for two functions, there may be a change in duties, responsibilities 2 cause changes in circumstances. Class can be refined based on abstract logic or business logic.

2, case presentations

Here and classes based refinement method can be selected according to the actual traffic.

class Animal {
    public void dogVoice (){
        System.out.println("狗叫声:旺旺");
    }
    public void cowVoice (){
        System.out.println("牛叫声:哞哞");
    }
}
class DogVoice {
    public String getDogVoice (){
        return "旺旺" ;
    }
}
class CowVoice {
    public String getCowVoice (){
        return "哞哞" ;
    }
}

3 Notes

Reduce code a program change caused by large-scale changes in circumstances, reduce the complexity of the class, the class improve readability and maintainability. Under normal circumstances, need to comply with the principle of single responsibility, may be appropriate in violation of the principle of single responsibility.

Second, the interface segregation principle

1, concept description

The client should not rely on its unwanted interfaces, a class dependent on another class, should be based on the smallest interface.

2, case presentations

interface ReadBlog {
    String getBlog () ;
}
interface AdminBlog {
    Boolean insertBlog () ;
    Boolean updateBlog () ;
    Boolean deleteBlog () ;
}
/**
 * 读者只开放博客阅读接口
 */
class Reader implements ReadBlog {
    @Override
    public String getBlog() {
        return null;
    }
}
/**
 * 管理员有博客全部的管理权限
 */
class AdminUser implements AdminBlog,ReadBlog {
    @Override
    public String getBlog() {
        return null;
    }
    @Override
    public Boolean insertBlog() {
        return null;
    }
    @Override
    public Boolean updateBlog() {
        return null;
    }
    @Override
    public Boolean deleteBlog() {
        return null;
    }
}

3 Notes

The smaller the particle size of the design of the interface, the application program the system more flexible, while the program structure to be flexible also means increased complexity, the development and understanding of the development difficulty becomes larger, reduced maintainability.

Third, the Dependency Inversion principle

1, concept description

Should not rely on low-level layer module module, both of which should rely Abstract; Abstract should not rely on the details, the details should depend Abstract; central idea is oriented programming interface.

2, case presentations

public class C01_FarmFactory {
    public static void main(String[] args) {
        Animal animal = new Dog() ;
        FarmFactory farm = new Farming() ;
        farm.breed(animal) ;
        animal = new Pig() ;
        farm.breed(animal) ;
    }
}
/**
 * 接口声明依赖对象
 */
interface FarmFactory {
    void breed (Animal animal) ;
}
class Farming implements FarmFactory {
    @Override
    public void breed(Animal animal) {
        System.out.println("农场饲养:"+animal.getAnimalName());
    }
}
interface Animal {
    String getAnimalName () ;
}
class Dog implements Animal {
    @Override
    public String getAnimalName() {
        return "牧羊犬";
    }
}
class Pig implements Animal {
    @Override
    public String getAnimalName() {
        return "土猪一号";
    }
}

3 Notes

With respect to the variability of the system development, abstract relatively stable. Abstract-based architecture to build a stable and flexible than detail-based architecture. The lower module must have as far as possible the abstract class or interface, better stability program. Declare the types of variables as much as possible is an abstract class or interface, this variable refers to the existence of a transitional space between the real and the objects, which will help the program expand and optimize.

Fourth, Richter substitution principle

1, concept description

Assume the following scenario:

  • Exist objects O1 a Tl type, and examples
  • Exists, a type T2, and instances of objects O2

If all types of objects O1 T1 are replaced with the object O2 of type T2, the behavior of the program does not change. T2 then the type is a subtype of type T1. In other words, all the local references of the base class must be used transparently object whose subclasses.

2, case presentations

public class C01_Calculate {
    public static void main(String[] args) {
        BizCalculate bizCalculate = new BizCalculate() ;
        System.out.println(bizCalculate.add(2,3));
    }
}
class Calculate { }
class BaseCalculate extends Calculate {
    public int add (int a,int b){
        return a+b;
    }
}
/**
 * 这里使用组合的方式完成计算
 */
class BizCalculate extends Calculate {
    private BaseCalculate baseCalculate = new BaseCalculate() ;
    public int add (int a,int b){
        return this.baseCalculate.add(a,b);
    }
}

3 Notes

When using inheritance, follow the Richter substitution principle, in a subclass try not to override the parent class; subclass can extend the functionality of the parent class, but can not change the original function of the parent class; in appropriate cases, by polymerizable, composition, etc. to solve the problem dependent.

Fifth, the principle of opening and closing

1, concept description

Opening and closing the most basic principles of programming, the most important design principles in the design of the code structure of the design should be considered open for extension, but closed for modification, abstract thinking to build the structure, specific implementation details of the extension.

2, case presentations

public class C01_BookPrice {
    public static void main(String[] args) {
        ParityBook parityBook = new DiscountBook("Java",100.00) ;
        System.out.println(parityBook.getPrice());
    }
}
interface Book {
    String getName () ;
    Double getPrice () ;
}
/**
 * 平价书籍
 */
class ParityBook implements Book {
    private String name ;
    private Double price ;
    public ParityBook(String name, Double price) {
        this.name = name;
        this.price = price;
    }
    @Override
    public String getName() {
        return this.name ;
    }
    @Override
    public Double getPrice() {
        return this.price ;
    }
}
/**
 * 打折数据扩展价格计算策略
 */
class DiscountBook extends ParityBook {
    public DiscountBook(String name, Double price) {
        super(name, price);
    }
    @Override
    public Double getPrice() {
        double oldPrice = super.getPrice();
        return oldPrice * 0.8 ;
    }
}

3 Notes

Based on the design principle of the opening and closing structure of the code reusability and maintainability can be improved through the interface or abstract class constraints may change the behavior of class changes behavior based on a specified policy package, and enables extended open design patterns The basic principle is to follow the principle of opening and closing.

Sixth, Dimmit principle

1, concept description

Dimitris principle called the least known principle that a class of their dependent classes know better. That is, for no matter how complex the dependent classes, as much as possible the internal logic is encapsulated in the class. In addition to the external public methods provided, not open to any information. The more closely the relationship between class and class, the greater the degree of coupling, the coupling of many ways, dependent, associated, combined, polymerization.

  • The concept of direct friends

There is coupling between two objects, say a friend relationship between the two objects. Which appears member variables, method arguments, method return values ​​in the class known as direct friends, now out of the local variables in the class are not direct friends. In principle, a strange kind is best not to appear as local variables within the class.

2, case presentations

public class C01_Employee {
    public static void main(String[] args) {
        HeadCompanyEmpManage empManage = new HeadCompanyEmpManage() ;
        BranchCompanyEmpManage branchEmp = new BranchCompanyEmpManage() ;
        empManage.printEmp(branchEmp);
    }
}
/**
 * 总公司员工
 */
class HeadCompanyEmp {
    public String name ;
    public HeadCompanyEmp(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "HeadCompanyEmp{name='" + name + '}';
    }
}
/**
 * 分公司员工
 */
class BranchCompanyEmp {
    public String name ;
    public BranchCompanyEmp(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "BranchCompanyEmp{name='" + name + '}';
    }
}
/**
 * 分公司员工管理
 */
class BranchCompanyEmpManage {
    // 添加分公司员工
    public List<BranchCompanyEmp> addEmp (){
        List<BranchCompanyEmp> list = new ArrayList<>() ;
        for (int i = 1 ; i <= 3 ; i++){
            list.add(new BranchCompanyEmp("分公司员工"+i)) ;
        }
        return list ;
    }
    // 获取分公司员工
    public void printBranchCompanyEmp (){
        List<BranchCompanyEmp> list = addEmp () ;
        for (BranchCompanyEmp emp:list){
            System.out.println(emp);
        }
    }
}
/**
 * 总公司员工管理,基于迪米特原则,不出现陌生类
 */
class HeadCompanyEmpManage {
    // 添加总公司员工
    public List<HeadCompanyEmp> addHeadEmp (){
        List<HeadCompanyEmp> list = new ArrayList<>() ;
        for (int i = 1 ; i <= 3 ; i++){
            list.add(new HeadCompanyEmp("总公司员工"+i)) ;
        }
        return list ;
    }
    public void printEmp (BranchCompanyEmpManage empManage){
        // 打印分公司员工
        empManage.printBranchCompanyEmp();
        List<HeadCompanyEmp> headEmpList = addHeadEmp () ;
        for (HeadCompanyEmp headCompanyEmp:headEmpList){
            System.out.println(headCompanyEmp);
        }
    }
}

3 Notes

Demeter principle intention is to reduce the coupling between classes, each class is reduced because unnecessary dependence coupling relationship can be reduced. Reducing the coupling relation is not completely required dependencies, excessive use of Demeter principle, easy to produce large amounts of the intermediate class, resulting in the complexity increases. Therefore, when using the Demeter principles should weigh based on actual business.

Seven principles of Design Summary

The core idea of ​​design patterns and design principles are: business applications judge may change module, and these modules independent, encapsulation based on specified policies, not to change those little modules are coupled together, the package ideologically based interfaces and abstract classes, rather than specific implementation program. The core aim is to reduce the degree of loose coupling between interacting objects. Design patterns and principles can not be applied mechanically formulas, personal understanding: As long as the shape, charm naturally not bad.

Eight, the source address

GitHub·地址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·地址
https://gitee.com/cicadasmile/model-arithmetic-parent

Guess you like

Origin www.cnblogs.com/cicada-smile/p/11974550.html
Recommended