面向对象七大原则

单一原则

对于类来说,即一个类只负责一项职责,如果A负责两个不同职责:职责1职责2,当职责1需求变更而改变职责A时,可能造成职责2执行错误,所以需要将A的力度分解为A1,A2

 

package test.single;

/*public class single1 {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("摩托车");
        vehicle.run("汽车");
        vehicle.run("飞机");
    }
}

class Vehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + "在公路上跑");
    }
}*/

/*
public class single1 {
    public static void main(String[] args) {
        RoadVehicle vehicle = new RoadVehicle();
        vehicle.run("摩托车");
        vehicle.run("汽车");
        AirVehicle airVehicle = new AirVehicle();
        airVehicle.run("飞机");
    }
}
//遵循单一职责
//但这样改动很大,即将类分解,同时修改客户端
class RoadVehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + "在公路上跑");
    }
}

class AirVehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + "天空飞行");
    }
}

class WaterVehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + "水中运行");
    }
}*/

public class single1 {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle.run("汽车");
        vehicle.AirRun("飞机");
        vehicle.WaterRun("轮船");
    }
}

//这种修改方法没有对原来的类做大的修改,只是增加方法
//这种虽然没有在类这个级别上遵守单一职责原则,但在方法级别上,任然遵守单一职责
class Vehicle {
    public void run(String vehicle) {
        System.out.println(vehicle + "在公路上跑");
    }

    public void AirRun(String vehicle) {
        System.out.println(vehicle + "在天上飞");
    }

    public void WaterRun(String vehicle) {
        System.out.println(vehicle + "在水中划");
    }
}
/**
 * 注意事项:
 * 单一职责原则注意事项和细节
 * 1 降低类的复杂度,一个类只负责一项职责。
 * 2 提高类的可读性,可维护性
 * 3 降低变更引起的风险
 * 4 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;只有类中方法数量足够少,
 * 可以在方法级别保持单一职责原则
 */

 

接口隔离原则 

客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上

类A通过接口 interface1 依赖 类B ,类C通过接口Interface1依赖类D,如果接口Interface1对于类A和类C来说不是最小接口那么类B和类D必须去实现他们不需要方法

按隔离原则应当这样处理:将接口interface1拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系,也就是采用接口隔离原则

package test.segregation;

/*public class Segregation1 {
    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();

    void operation2();

    void operation3();

    void operation4();

    void operation5();
}

class B implements Interface1 {

    @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");
    }

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

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

class D implements Interface1 {

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

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

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

    @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(Interface1 i) {
        i.operation2();
    }

    public void depend3(Interface1 i) {
        i.operation3();
    }
}

class C {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend4(Interface1 i) {
        i.operation4();
    }

    public void depend5(Interface1 i) {
        i.operation5();
    }
}*/
//把接口拆分成三个需要用到那个接口就实现那个接口,降低了接口之间的松耦合
public class Segregation1 {
    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();
    }
}

依赖倒置

高层模块不应该依赖底层模块,二者应该依赖其抽象

抽象不应该依赖细节,细节应该依赖抽象

依赖倒置的中心思想是面向接口编程

依赖倒转原则是基于这样的设计理念;相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多,在Java中,抽象指的是接口或抽象类,细节就是具体的实现类

使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成

 

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

 class Email {
 public String getInfo() {
 return "电子邮件信息:hello,world";
 }
 }

 */

/**
 class Person {
 public void receive(Email email) {
 System.out.println(email.getInfo());
 }
 }*/

/*
public class DependentInversion {
    public static void main(String[] args) {
        Person person = new Person();
        person.receive(new Email());
        person.receive(new WeiXin());
    }
}

interface IReceiver {
    public String getInfo();
}

class Email implements IReceiver {

    @Override
    public String getInfo() {
        return "电子邮件信息:hello world";
    }
}

//增加微信
class WeiXin implements IReceiver {

    @Override
    public String getInfo() {
        return "微信信息:hello world";
    }
}

class Person {
    public void receive(IReceiver receiver) {
        System.out.println(receiver.getInfo());
    }
}*/

/**
 * 依赖倒置的三种方式
 * 接口传递
 * 构造方法传递
 * setter方式传递
 */
/*
//接口方式
public class DependentInversion {
    public static void main(String[] args) {
        OpenAndClose openAndClose = new OpenAndClose();
        openAndClose.open(new ChangHong());
        openAndClose.open(new WangPai());
    }
}

interface IOpenAndClose {
    public void open(ITV tv);
}

interface ITV {
    public void play();
}

class ChangHong implements ITV {

    @Override
    public void play() {
        System.out.println("长虹电视机, 打开");
    }
}

class WangPai implements ITV {

    @Override
    public void play() {
        System.out.println("王牌电视机, 打开");
    }
}

class OpenAndClose implements IOpenAndClose {

    @Override
    public void open(ITV tv) {
        tv.play();
    }
}*/
//构造方法
/*
public class DependentInversion {
    public static void main(String[] args) {
        OpenAndClose openAndClose = new OpenAndClose();
        openAndClose.OpenAndClose(new ChangHong());
        openAndClose.open();
        openAndClose.OpenAndClose(new WangPai());
        openAndClose.open();
    }
}

interface IOpenAndClose {
    public void open();
}

interface ITV {
    public void play();
}

class ChangHong implements ITV {

    @Override
    public void play() {
        System.out.println("hello 长虹");
    }
}

class WangPai implements ITV {

    @Override
    public void play() {
        System.out.println("hello 王牌");
    }
}

class OpenAndClose implements IOpenAndClose {

    public ITV tv;

    public void OpenAndClose(ITV tv) {
        this.tv = tv;
    }

    @Override
    public void open() {
        this.tv.play();
    }
}*/
//方式三 通过setter方法传递
public class DependentInversion {
    public static void main(String[] args) {
        OpenAndClose openAndClose = new OpenAndClose();
        openAndClose.setTv(new WangPai());
        openAndClose.open();
        openAndClose.setTv(new ChangHong());
        openAndClose.open();
    }
}

interface IOpenAndClose {
    public void open();

    public void setTv(ITV tv);
}

interface ITV {
    public void play();
}

class ChangHong implements ITV {

    @Override
    public void play() {
        System.out.println("长虹电视机");
    }
}

class WangPai implements ITV {

    @Override
    public void play() {
        System.out.println("王牌电视机");
    }
}

class OpenAndClose implements IOpenAndClose {

    private ITV tv;

    @Override
    public void setTv(ITV tv) {
        this.tv = tv;
    }

    @Override
    public void open() {
        this.tv.play();
    }
}

里式替换

OO中的继承性的思考和说明
1) 继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。
2) 继承在给程序设计带来便利的同时,也带来了弊端。比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有
的子类,并且父类修改后,所有涉及到子类的功能都有可能产生故障

3)所有引用基类的 地方必须能透明地使用其子类的对象。

4) 在使用继承时,遵循里氏替换原则,在子类中尽量不要重 写父类的方法

5) 里氏替换原则告诉我们,继承实际上让两个类耦合性增强了, 在适当的情况下,可以通过聚合,组合,依赖 来解决问题。.

6) 问题提出:在编程中,如何正确的使用继承? => 里氏替换原则

package test.liskov;

/*
public class Liskov {
    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));//这里本意是求出 11-3
        System.out.println("1-8=" + b.func1(1, 8));
        System.out.println("11+3+9=" + b.func2(11, 8));
    }
}

class A {
    //返回两个数的差
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}
//B类继承了A
//增加了一个新功能:完成两个数相加,然后和9求和
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;
    }
}*/
public class Liskov {
    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+8+9=" + b.func2(11, 8));
        //使用组合仍然可以调用 A的相关方法
        System.out.println("11-9=" + b.func3(11, 9));
    }
}

class Base {

}

class A extends Base {
    public int func1(int num1, int num2) {
        return num1 - num2;
    }
}

class B extends Base {
    //如果B需要使用A类的方法需要使用组合关系
    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;
    }

    //我们仍然想使用A的方法
    public int func3(int a, int b) {
        return this.a.func1(a, b);
    }
}

开闭原则 

1)开闭原则是编程中最基础,最重要的设计原则

2)一个软件实体如类,模块和函数应该对扩展开放(提供方),对修改关闭(使用方)。用抽象构建框架,用实现扩展细节

3)当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改现有的代码实现变化。

4)编程遵循其它原则,以及使用设计模式的目的就是遵循开闭原则。

package test.ocp;

/*方式一原则
1)优点是比较好理解,简单易操作
2)缺点是违反了设计模式的ocp,即对扩展开放(提供方),对修改关闭(使用方)。
3)即当我们给类增加新功能的时候,尽量不修改代码,或者尽量少修改代码。
4)比如我们这时要新增加一个图形种类 三角形,我们修改的地方就比较多*/
/*
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);
        } else if (s.m_type == 3) {
            drawTriangle(s);
        }
    }

    public void drawRectangle(Shape r) {
        System.out.println("绘制矩形");
    }

    public void drawCircle(Shape r) {
        System.out.println("绘制圆形");
    }

    public void drawTriangle(Shape r) {
        System.out.println("绘制三角形");
    }
}

class Shape {
    int m_type;
}

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

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

//新增三角形
class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }
}*/
/*方式二
改进的思路分析
1)把创建Shape的类做成抽象类,并且提供一个抽象的draw方法,让类去实现即可
2)这样我们有新的图形类时,只需要让新的图形类继承Shape,并实现draw方法即可
3)使用方的代码就不需要修改->满足了开闭原则*/
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());
        graphicEditor.drawShape(new OtherGraphic());
    }
}

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

abstract class Shape {
    int m_type;

    public abstract void draw();
}

class Rectangle extends Shape {

    Rectangle() {
        super.m_type = 1;
    }

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

class Circle extends Shape {

    Circle() {
        super.m_type = 2;
    }

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

class Triangle extends Shape {

    Triangle() {
        super.m_type = 3;
    }

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

class OtherGraphic extends Shape {

    OtherGraphic() {
        super.m_type = 4;
    }

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

 

迪米特法则

1) 一个对象应该对其他对象保持最少的了解
2) 类与类关系越密切,耦合度越大
3) 迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public 方法,不对外泄露任何信息
4) 迪米特法则还有个更简单的定义:只与直接的朋友通信
5) 直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的
内部。

 

package test.demeter;

import java.util.ArrayList;
import java.util.List;

/*
public class Demeter {
    public static void main(String[] args) {
        //创建一个学校管理类
        SchoolManger schoolManger = new SchoolManger();
        //输出学院的员工ID 和 学院总部的ID
        schoolManger.printAllEmployee(new CollegeManager());
    }
}

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

    public String getId() {
        return id;
    }

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

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

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = 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 SchoolManger {
    //返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();
        for (int i = 0; i < 5; i++) {
            Employee emp = new Employee();
            emp.setId("学校总部员工ID=" + i);
            list.add(emp);
        }
        return list;
    }

    //完成输出学校总部和学院员工信息的方法
    void printAllEmployee(CollegeManager sub) {
        //分析问题
        //1 这里的 CollegeEmployee 不是 SchoolManger 的直接朋友
        //2 CollegeEmployee 是以局部变量的方式出现在 SchoolManger
        //3 违反了迪米特法则
        //获取到学院员工
        List<CollegeEmployee> list1 = sub.getAllEmployee();
        System.out.println("----------学院员工----------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
        //获取到学校总部的员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("----------学校总部员工--------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }


}*/
//方式二 迪米特法则改进
public class Demeter {
    public static void main(String[] args) {
        //创建一个学校管理类
        SchoolManger schoolManger = new SchoolManger();
        //输出学院的员工ID 和 学院总部的ID
        schoolManger.printAllEmployee(new CollegeManager());
    }
}

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

    public String getId() {
        return id;
    }

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

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

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = 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 printEmployee() {
        List<CollegeEmployee> list1 = getAllEmployee();
        System.out.println("----------学院员工----------");
        for (CollegeEmployee e : list1) {
            System.out.println(e.getId());
        }
    }
}

//学校的管理类
class SchoolManger {
    //返回学校总部的员工
    public List<Employee> getAllEmployee() {
        List<Employee> list = new ArrayList<Employee>();
        for (int i = 0; i < 5; i++) {
            Employee emp = new Employee();
            emp.setId("学校总部员工ID=" + i);
            list.add(emp);
        }
        return list;
    }

    //完成输出学校总部和学院员工信息的方法
    void printAllEmployee(CollegeManager sub) {
        //分析问题
        //将 输出 学院员工的方法,封装到 CollegeManger
        sub.printEmployee();
        //获取到学校总部的员工
        List<Employee> list2 = this.getAllEmployee();
        System.out.println("----------学校总部员工--------------");
        for (Employee e : list2) {
            System.out.println(e.getId());
        }
    }


}

 

合成复用原则

尽量使用合成/聚合的方式,而不使用继承


已有 0 条评论

    欢迎您,新朋友,感谢参与互动!