工具利器收藏ios

设计模式七大原则

2019-11-23  本文已影响0人  iYeso

设计模式七大原则

设计模式体现了代码的耦合性, 内聚性以及可维护性,可扩展性,重用性,灵活性。

一、单一职责原则(Single responsibility)

单一职责原则注意事项和细节:

/**
 * @author Yu
 * 只有类中方法数量足够少,可以在方法级别保持单一职责原则
 */
public class SingleResponsility {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("布加迪威龙");
        vehicle.fly("波音747");
    }
}

// 逻辑简单,方法级别实现单一职责
// 逻辑复杂,分类实现单一职责
class Vehicle {

    public void run(String string) {
        System.out.println(string + ":是陆地交通工具");
    }

    public void fly(String string) {
        System.out.println(string + ":是空中交通工具");
    }
}

二、接口隔离原则(Interface Segregation)

image
public class InterfaceSegregation {
    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B());
        a.depend2(new B());
        a.depend3(new B());

        C c = new C();
        c.depend1(new D());
        c.depend4(new D());
        c.depend5(new D());
    }
}

interface interface1 {
    void Operation1();
}

interface interface2 {
    void Operation2();

    void Operation3();
}

interface interface3 {
    void Operation4();

    void Operation5();
}

class B implements interface1, interface2 {

    @Override
    public void Operation1() {
        System.out.println("B 实现了 Operation1");
    }

    @Override
    public void Operation2() {
        System.out.println("B 实现了 Operation2");
    }

    @Override
    public void Operation3() {
        System.out.println("B 实现了 Operation3");
    }
}

class D implements interface1, interface3 {

    @Override
    public void Operation1() {
        System.out.println("D 实现了 Operation1");
    }

    @Override
    public void Operation4() {
        System.out.println("D 实现了 Operation4");
    }

    @Override
    public void Operation5() {
        System.out.println("D 实现了 Operation5");
    }
}

class A {

    public void depend1(interface1 i) {
        i.Operation1();
    }

    public void depend2(interface2 i) {
        i.Operation2();
    }

    public void depend3(interface2 i) {
        i.Operation3();
    }
}

class C {

    public void depend1(interface1 i) {
        i.Operation1();
    }

    public void depend4(interface3 i) {
        i.Operation4();
    }

    public void depend5(interface3 i) {
        i.Operation5();
    }
}

三、依赖倒转原则(Dependence Inversion)

依赖关系三种传递方式:

public class DependenceInversion {
    public static void main(String[] args) {
        Person person = new Person();
        person.receive(new Email());
        person.receive(new WeChat());
    }
}

interface Info{
    String getInfo();
}

class Email implements Info{

    @Override
    public String getInfo() {
        return "Receive Email";
    }
}

class WeChat implements Info{

    @Override
    public String getInfo() {
        return "Receive WeChat";
    }
}

//person 接受信息
class Person {

    public void receive(Info info) {
        System.out.println(info.getInfo());
    }
}

四、里氏替换原则(Liskov Substitution)

public class LiskovSubstitution {
    public static void main(String[] args) {
        A a = new A();
        System.out.println("2-1=" + a.func1(2, 1));

        B b = new B();
        System.out.println("2+1=" + b.func1(2, 1));
        System.out.println("2+1+9=" + b.func2(2, 1));
        System.out.println("B类使用A类方法:2-1=" + b.func3(2, 1));
    }
}

class Base {
    //把基础方法和成员抽取成基类
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}

class A extends Base {

//    public int func1(int num1, int num2) {
//        return num1 - num2;
//    }
}

class B extends Base {

      // TODO 类 B `无意` 重写了父类 A 方法,造成原有方法发生改变。
//    @Override
//    public int func1(int num1, int num2) {
//        return num1 + num2;
//    }

    @Override
    public int func1(int num1, int num2) {
        return num1 + num2;
    }

    public int func2(int num1, int num2) {
        return func1(num1, num2) + 9;
    }

    private A a = new A();//组合

    //使用 A 方法
    public int func3(int num1, int num2) {
        return this.a.func1(num1, num2);
    }
}

五、开闭原则 OCP(Open Closed)

public class OpenClosed {
    public static void main(String[] args) {
        Use use = new Use();
        use.drawShape(new Triangle());
        use.drawShape(new Circle());
        use.drawShape(new OtherGraphics());//只需要让 此类继承 抽象类,子类实现具体方法  OCP原则
    }
}

class Use {
    public void drawShape(Shape shape) {
        shape.draw();
    }
}

abstract class Shape {
    public abstract void draw();
}

class Triangle extends Shape {

    @Override
    public void draw() {
        System.out.println("子类实现具体功能:三角形");
    }
}

class Circle extends Shape {

    @Override
    public void draw() {
        System.out.println("子类实现具体功能:圆形");
    }
}

class OtherGraphics extends Shape {

    @Override
    public void draw() {
        System.out.println("子类实现具体功能:任何形状");
    }
}

六、迪米特法则(Demeter)

class A{
    B b;//全局变量 - 直接朋友
    public B m1(){} //方法返回值 - 直接朋友
    public void m2(B b){}//方法入参 - 直接朋友
    public void m3(){
        B b1 = new B();// 局部变量 非直接朋友
    }
}
public class Demeter {
    public static void main(String[] args) {
        SchoolManager schoolManager = new SchoolManager();
        schoolManager.printAllEmployee(new CollegeManager());
    }
}

//学院员工类
class CollegeEmployee {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

//管理学院员工的管理类:
class CollegeManager {
    //返回学院的所有员工 //TODO CollegeEmployee 直接朋友
    public List<CollegeEmployee> getAllEmployee() {
        List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
        for (int i = 0; i < 10; i++) { //这里我们增加了10 个员工到list ,
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id " + i);
            list.add(emp);
        }
        return list;
    }

    public void printCollegeEmployee() {
        List<CollegeEmployee> list1 = this.getAllEmployee();
        System.out.println("---学院员工----");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
    }
}

//学校总部员工类
class SchoolEmployee {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

//学校管理类
//TODO 直接朋友 Employee CollegeManager
class SchoolManager {
    //返回学校总部的员工
    public List<SchoolEmployee> getAllEmployee() {
        List<SchoolEmployee> list = new ArrayList<SchoolEmployee>();
        for (int i = 0; i < 5; i++) { //这里我们增加了5个员工到list
            SchoolEmployee emp = new SchoolEmployee();
            emp.setId("学校总部员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    //该方法完成输出学校总部和学院员工信息(id)
    void printAllEmployee(CollegeManager sub) {
        //获取到学院员工
        //TODO 非直接朋友 CollegeEmployee  应该提取到  CollegeManager
//        List<CollegeEmployee> list1 = sub.getAllEmployee();
//        System.out.println("---学院员工----");
//        for (CollegeEmployee e : list1) {
//            System.out.println(e.getId());
//        }
        sub.printCollegeEmployee();//只提供方法,不把具体实现放在其他类里面。

        //获取到学校总部员工
        List<SchoolEmployee> list2 = this.getAllEmployee();
        System.out.println("------学校总部员工------");
        for (SchoolEmployee e : list2) {
            System.out.println(e.getId());
        }
    }
}

七、合成复用原则(Composite Reuse)

合成复用原则 尽量使用组合/聚合的方式,而不是使用继承。

public class CompositeReuse {
    public static void main(String[] args) {
        System.out.println("------依赖------");
        B b = new B();
        b.Operation1(new A());

        System.out.println("------聚合------");
        b.setA(new A());
        b.Operation2();

        System.out.println("------组合------");
        b.Operation3();
    }
}

class A {
    void Operation1() {
        System.out.println("A Operation1");
    }

    void Operation2() {
        System.out.println("A Operation2");
    }

    void Operation3() {
        System.out.println("A Operation3");
    }
}

//如果只是需要用到 A类的方法,尽量不要使用继承。而是使用,依赖,聚合,组合的方式
class B {
    void Operation1(A a) {//TODO 依赖
        a.Operation1();
        a.Operation2();
        a.Operation3();
    }

    //==============================================================
    A a;
    public void setA(A a) {
        this.a = a;
    }

    void Operation2() {//TODO 聚合
        a.Operation1();
        a.Operation2();
        a.Operation3();
    }

    //==============================================================
    A a1 = new A();

    void Operation3() {//TODO 组合
        a1.Operation1();
        a1.Operation2();
        a1.Operation3();
    }
}

八: UML(Unified Modeling Language)

IDEA PlantUML表示类与类之间的关系的符号

@startuml

Class1 <|-- ClassA:泛化
Class2 <-- ClassB:关联
Class3 *-- ClassC:组合
Class4 o-- ClassD:聚合
Class5 <|.. ClassE:实现
Class6 <.. ClassF:依赖

@enduml
image
8.1: 依赖(Dependence)

只要是在类中用到了对方,那么他们之间就存在依赖关系。如果没有对方,连编绎都通过不了。

image
/**
 * @author Yu
 * 类中用到了对方;
 * 类的成员属性;
 * 方法的返回类型;
 * 方法接收的参数类型;
 * 方法中使用到;
 */
public class Dependence {
    A a;//TODO 类的成员属性

    public A save(B b) {//TODO 方法接收的参数类型
        //TODO 方法的返回类型
        System.out.println("");
        A a = new A();//TODO 方法中使用到
        return a;
    }
}

class A {}

class B {}
8.2: 继承(泛化 Generalization)

泛化关系实际上就是继承关系,依赖关系的特例。

image
public class Generalization extends Base {

    @Override
    public void get(Object oId) {

    }

    @Override
    public void put(Object oName) {

    }
}

abstract class Base {
    abstract public void get(Object oId);

    abstract public void put(Object oName);
}
8.3: 实现(Realization)

实现关系实际上就是 A类 实现 B接口,依赖关系的特例。

image
public class Implementation implements Base {
    @Override
    public void init() {
        System.out.println("init");
    }
}

interface Base {
    void init();
}
8.3: 关联(Association)

类与类之间的关系,依赖关系的特例。

关联具有导航性:即双向关系或单向关系。

image
public class Person {
    private IDCard idCard;
}

class IDCard {
    //private Person person;
}
8.4: 聚合(Aggregation)

表示的是整体和部分的关系,整体与部分可以分开,关联关系的特例。

聚合关系是关联关系的特例,所以他具有关联的导航性与多重性。

image
public class Computer {
    private Mouse mouse;
    private Keyboard keyboard;

    public void setMouse(Mouse mouse) {
        this.mouse = mouse;
    }

    public void setKeyboard(Keyboard keyboard) {
        this.keyboard = keyboard;
    }
}

class Mouse {}

class Keyboard {}

组合(Composite)

整体与部分的关系,但是整体与部分不可以分开,关联关系的特例。

级联删除就是组合关系。

image
public class Computer {
   private CPU cpu = new CPU();
   private SSD ssd = new SSD();
}

class CPU {}

class SSD {}
上一篇 下一篇

猜你喜欢

热点阅读