里氏替换原则
-
-
-
package com.designPatter.liskov; /** *里氏替换原则 * * @author L * */ public class Liskov { public static void main(String[] args) { // TODO Auto-generated method stub A a = new A(); System.out.println("11-3=" +a.func1(11, 3)); B b = new B(); // System.out.println("9-2=" + b.func1(9, 2)); int i = b.func3(11, 3); System.out.println(i); } } //创建一个更加基础的类 class Base{ } class A extends Base{ public int func1(int a,int b) { return a-b; } } class B extends Base{ private A a = new A(); public int func3(int a ,int b) { return this.a.func1(a, b); } public int func1(int a,int b) { return a +b; } public int func2(int a,int b ) { return func1(a, b)+9; } }
开闭原则
-
-
-
package com.designPatter.ocp; /** * 开闭原则 * 给类增加新的功能是,尽量不改变代码,而扩展功能 * * @author L * */ public class Ocp { public static void main(String[] args) { Graph graph = new Graph(); graph.drawShape(new rectangle()); graph.drawShape(new cricle()); } } class Graph{ public void drawShape(shape s) { s.draw(); } } abstract class shape{ int m_shape; public abstract void draw();//抽象方法 } class rectangle extends shape{ @Override public void draw() { // TODO Auto-generated method stub System.out.println("绘制三角形"); } rectangle(){ super.m_shape = 1; } } class cricle extends shape{ @Override public void draw() { // TODO Auto-generated method stub System.out.println("绘制圆形"); } cricle(){ super.m_shape = 2; } }
迪米特法则
-
-
-
package com.designPatter.Demeter; import java.util.ArrayList; import java.util.List; /** * 迪米特原则 * 降低类和类的耦合性 * 最少知道原则 * 对自己依赖的类越少越好 * 直接朋友:成员变量 返回值 方法参数 * * @author L * */ public class demeter { public static void main(String[] args) { // TODO Auto-generated method stub SchoolManger schoolManger = new SchoolManger(); System.out.println("学校信息------"); schoolManger.printEmployee(new CollegeManger()); } } class Employee{ private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } class CollegeEmployee{ private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } class CollegeManger{ //返回员工信息 public List<CollegeEmployee> getAllEmployee(){ List<CollegeEmployee> list = new ArrayList<>(); for (int i = 1; i <= 5; i++) { CollegeEmployee employee = new CollegeEmployee(); employee.setId(i); list.add(employee); } return list; } //打印信息 public void printEmployee(){ List<CollegeEmployee> list = this.getAllEmployee(); System.out.println("学院员工信息:-------"); for (CollegeEmployee employee :list) { System.out.println("员工编号"+employee.getId()); } } } class SchoolManger{ //返回所有员工信息 public List<Employee> getAllEmployee(){ List<Employee> list = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Employee emp = new Employee(); emp.setId(i); list.add(emp); } return list; } public void printEmployee(CollegeManger sub){ //调用学院的信息 sub.printEmployee(); //学院信息 List<Employee> list = this.getAllEmployee(); System.out.println("学校管理员工信息-----"); for (Employee employee :list) { System.out.println("管理员编号"+employee.getId()); } } }
合成复用原则
-
不推荐使用继承,而是聚合,组合
-
-