设计模式七大原则

所谓设计模式,其实是总结出了一套能够通用的软件设计规范的参考。在编写软件过程中,如何提高代码的重用性,可读性,拓展性与可靠性,这都是设计模式需要解决的问题。设计模式包含了面向对象的精髓。

设计模式的原则主要有七种:

1)单一职责原则:对类来说,一个类只负责一项原则,如A负责两个不同职责:职责1和职责2,当职责1的需求改变而改变A的时候可能造成职责2错误,所以需要把类A分解成A1和A2.

2)接口隔离原则:一个类对于另一个类的依赖应该建立在最小的接口上。

                                         

比如上面这张图,在传统模式中,如果A和C分别调用通过interface1的123和145,而且A通过B依赖接口1,C通过D依赖接口1.也就是说,BD分别需要implements接口1的5中方法,然后AC再依赖BD调用这个接口。

本身这种方法很直观,但是有问题:对于A来说他并不需要接口1中的4 5两种方法;对于C来说,他并不需要接口2 3两种方法。那么上面多余的办法就是一种浪费。如何解决上面的浪费呢?也就是使用接口隔离原则来设计:

                                            

在使用接口隔离的设计原则中,原来的接口被分割成三个接口,这样A只需要使用接口1和2,C只需要使用接口1和3.这样AC分别依赖BD实现对于3个接口的调用,使得接口隔离。BD也只需要分别实现operation123和operation14即可。代码如下:

package com.principle.segration;

public class segration {
    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{
    public void operation1(){
        System.out.println("B implements interface1");
    }
    public void operation2(){
        System.out.println("B implements interface2");
    }
    public void operation3(){
        System.out.println("B implements interface3");
    }
}

class D implements Interface1,Interface3{
    public void operation1(){
        System.out.println("D implements interface1");
    }
    public void operation4(){
        System.out.println("D implements interface4");
    }
    public void operation5(){
        System.out.println("D implements interface5");
    }
}

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();
    }
}

3)依赖倒转原则:高层模块不应该依赖底层模块,二者都应该依赖其抽象。细节应该依赖抽象,依赖倒转原则的核心是面向接口编程。

4)里式替换原则:里式替换原则规定了编程中如何正确使用继承。继承会使得程序的可以执行降低,增加对象间的耦合性。如果一个类被其他类所继承,当这个类需要修改时,必须考虑所有子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障。

        里式替换原则的要求是:所有引用基类的地方必须透明地使用子类的对象,也就是子类对象不能够随随便便修改基类对象的功能,否则继承就没有意义了,为什么不重写一个新的方法?所以继承实际上让两个类的耦合性增强了,在适当的情况下可以用聚合和组合的方式来解决问题。

package com.principle.liskov;

public class liskov1 {
    public static void main(String []args){
        A a = new A();
        System.out.println("11-3=" + a.func1(11,3));
        System.out.println("1-8=" + a.func1(1,8));
        System.out.println("------------");
        B b = new B();
        System.out.println("11-3=" + b.func1(11,3));
        System.out.println("1-8=" + b.func1(1,8));
        System.out.println("11+3+9=" + b.func2(11,3));
    }
}
class A{
    public int func1(int num1, int num2){
        return num1 - num2;
    }
}
/*在这里,B继承自A,但是B把A类中的func1功能修改了。实际上func2中的func1(a,b)是实现了a+b的功能然后再加9,而不是正常理解的A中的a-b。那么这样违反了历史原则,因为你改变函数功能了,那为什么不重写一个func3而是重载func1?这样会对原来A基类的功能造成歧义*/
class B extends A{
    public int func1(int a, int b){
        return a + b;
    }
    public int func2(int a, int b){
        return func1(a, b) + 9;
    }
}

使用历史原则编写的代码如下:

package com.principle.liskov.improve;

public class liskov1 {
    public static void main(String []args){
        A a = new A();
        System.out.println("11-3=" + a.func1(11,3));
        System.out.println("1-8=" + a.func1(1,8));
        System.out.println("------------");
        B b = new B();
        System.out.println("11-3=" + b.func1(11,3));
        System.out.println("1-8=" + b.func1(1,8));
        System.out.println("11+3+9=" + b.func2(11,3));
        System.out.println(b.func3(1,3));
    }
}
class Base{

}
/*AB都是从Base类继承而来,因为func1的功能不同了,所以没必要从A继承出B。AB之间的关系更接近聚合关系,而不是继承这种强耦合*/
class A extends Base{
    public int func1(int num1, int num2){
        return num1 - num2;
    }
}

class B extends Base{
    private A a = new A();
    public int func1(int a, int b){
        return a + b;
    }
    public int func2(int a, int b){
        return func1(a, b) + 9;
    }
    public int func3(int a, int b){
        return this.a.func1(a,b);
    }
}

 

5)开闭原则:一个软件的实体类,模块和函数,他们应该对拓展开放,对修改关闭。当软件变化时候,尽量通过拓展软件实体的行为来实现变化,而不是通过修改已经有的代码实现对变化。

比如说一个画图类:

package com.principle.openclose;
//不满足开闭原则的代码:画不同图形,用drawshape函数来判断是什么图形进而调用不同函数;这样拓展性非常差,不满足开闭原则
public class ocp {
    public static void main(String []args){
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }
}

class GraphicEditor{
    public void drawShape(Shape s){
        if(s.m_type == 1)
            drawRectangle(s);
        else if(s.m_type == 2)
            drawCircle(s);
        //1. 需要修改这里,当出现新的type需要画出三角形
        else if(s.m_type == 3)
            drawTriangle(s);
    }
    public void drawRectangle(Shape r){
        System.out.println("矩形");
    }
    public void drawCircle(Shape r){
        System.out.println("圆形");
    }
    //2. 修改这里,增加画三角形的函数
    public void drawTriangle(Shape r){
        System.out.println("三角形");
    }
}

class Shape{
    int m_type;
}
class Rectangle extends Shape{
    Rectangle(){
        m_type = 1;
    }
}
class Circle extends Shape{
    Circle(){
        m_type = 2;
    }
}

//当我们增加了一个三角形,那么除了增加下面这个三角形类之外,还需要修改:上面的1,2部分,这太复杂了,尤其是drawshape修改函数,不满足开闭原则
class Triangle extends Shape{
    Triangle(){
        m_type = 3;
    }
}

那么满足开闭原则的应该怎么改了呢?这里应该用到抽象类和抽象方法:

package com.principle.openclose.improve;

public class ocp {
    public static void main(String []args){
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
    }
}

class GraphicEditor{
    public void drawShape(Shape s){
        s.draw();
    }

}
//通过抽象类的方法实现对于三角形的拓展,实际上只需要增加三角形这一个抽象类并重写draw方法即可。这样满足开闭原则,方便拓展
abstract class Shape{
    int m_type;
    public abstract void draw();
}

class Rectangle extends Shape{
    Rectangle(){
        m_type = 1;
    }

    @Override
    public void draw() {
        System.out.println("绘制矩形");
    }
}

class Circle extends Shape{
    Circle(){
        m_type = 2;
    }

    @Override
    public void draw() {
        System.out.println("绘制圆形");
    }
}

class Triangle extends Shape{
    Triangle(){
        m_type = 3;
    }

    @Override
    public void draw() {
        System.out.println("绘制三角形");
    }
}

6)迪米特法则:迪米特法则的核心是降低类之间的耦合,所以也称最小知道原则,对自己依赖的类知道的越少越好。具体说,两个类之间应该减少不必要的依赖,从而降低耦合,并不是说完全摆脱依赖关系。

比如说下面的代码就有一些问题:

package com.principle.demeter;
import java.util.ArrayList;
import java.util.List;
/*重点看SchoolManager打印所有对象这一功能*/
public class Demeter1 {
    public static void main(String []args){
        SchoolManager schoolManager = new SchoolManager();
        schoolManager.printAllEmployee(new CollegeManager());
    }
}
class Employee{
    private String id;
    public void setId(String id){
        this.id = id;
    }
    public String getId(){
        return this.id;
    }
}
class CollegeEmployee{
    private String id;
    public  void setId(String id){
        this.id = id;
    }
    public String getId(){
        return this.id;
    }
}
class CollegeManager{
    public List<CollegeEmployee> getAllEmployee(){
        List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
        for(int i = 0; i < 10; i++){
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }
}

class SchoolManager{
    public List<Employee> getAllEmployee(){
        List<Employee> list = new ArrayList<Employee>();
        for(int i = 0; i < 10; i++){
            Employee emp = new Employee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }

    void printAllEmployee(CollegeManager sub){
        //在这里,CollegeEmployee是Schoolmanager类的间接朋友,而迪米特法则不希望
        //出现这种间接朋友,希望降低耦合。所以希望用一个接口直接把输出list1实现了,而不是在这里自己用间接朋友打印的形式
        List<CollegeEmployee> list1 = sub.getAllEmployee();
        System.out.println("-------fengongsiyuangong");
        for(CollegeEmployee e : list1){
            System.out.println(e.getId());
        }
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("----------xuexiaozongbuyuangong---");
        for(Employee e : list2){
            System.out.println(e.getId());
        }
    }
}

对于schoolmanager的打印,本身不应该让他知道CollegeEmployee的信息,因为他们这属于间接朋友了。所以应该改正如下:

package com.principle.demeter.improve;
import java.util.ArrayList;
import java.util.List;

public class Demeter1 {
    public static void main(String []args){
        SchoolManager schoolManager = new SchoolManager();
        schoolManager.printAllEmployee(new CollegeManager());
    }
}

class Employee{
    private String id;
    public void setId(String id){
        this.id = id;
    }
    public String getId(){
        return this.id;
    }
}

class CollegeEmployee{
    private String id;
    public  void setId(String id){
        this.id = id;
    }
    public String getId(){
        return this.id;
    }
}

class CollegeManager{
    public List<CollegeEmployee> getAllEmployee(){
        List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
        for(int i = 0; i < 10; i++){
            CollegeEmployee emp = new CollegeEmployee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }
    public  void printAllEmployee(){
        List<CollegeEmployee> list1 = this.getAllEmployee();
        System.out.println("-------fengongsiyuangong");
        for(CollegeEmployee e : list1){
            System.out.println(e.getId());
        }
    }
}

class SchoolManager{
    public List<Employee> getAllEmployee(){
        List<Employee> list = new ArrayList<Employee>();
        for(int i = 0; i < 10; i++){
            Employee emp = new Employee();
            emp.setId("学院员工id= " + i);
            list.add(emp);
        }
        return list;
    }
    void printAllEmployee(CollegeManager sub){
        //直接调用接口,避免生成间接朋友
        sub.printAllEmployee();

        List<Employee> list2 = this.getAllEmployee();
        System.out.println("----------xuexiaozongbuyuangong---");
        for(Employee e : list2){
            System.out.println(e.getId());
        }
    }
}

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

我们举个例子,假设B要用到A类的方法,最朴素的想法是用B继承A:

                                                                                    

但是这样的问题是耦合性太强了。B可能会影响到A。所以应该降低耦合,用依赖或者组合的关系:

                                                               

上面是依赖,也就是方法中直接把A类对象作为参数传进去;下面是聚合,也就是把A对象定义成 B的成员对象,然后调用即可。

 

其实综合来看,设计模式的七大原则的核心思想就是:

1.把应用中可能变化之处独立出来,不要把这些可能变化的和不需要变化的放在一起。

2.针对接口编程,而不是针对实现编程。

3. 交互对象应该为了松耦合而设计。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值