1、開閉原則(Open-closed Principle)
開閉原則,是面向設(shè)計中最基礎(chǔ)的設(shè)計原則。
一個軟件實體類、模塊、函數(shù)應(yīng)該對擴(kuò)展開放、對修改關(guān)閉。
強(qiáng)調(diào)的是用抽象構(gòu)建框架,用實現(xiàn)擴(kuò)展細(xì)節(jié)。可以提高軟件系統(tǒng)的可復(fù)用性和可維護(hù)性。
實例:文章來源:http://www.zghlxwxcb.cn/news/detail-606819.html
public interface ICourse {
Integer getId();
String getName();
Double getPrice();
}
public class JavaCourse implements ICourse{
private Integer id;
private String name;
private Double price;
public Integer getId() {
return this.id;
}
public String getName() {
return this.name;
}
public Double getPrice() {
return this.price;
}
public JavaCourse(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class JavaDiscountCourse extends JavaCourse {
public JavaDiscountCourse(Integer id, String name, Double price) {
super(id, name, price);
}
public Double getOriginPrice() {
return super.getPrice();
}
public Double getPrice() {
return super.getPrice() * 0.6;
}
}
2、本末倒置原則(Dependence Inversion Principle)
高層模塊不應(yīng)該依賴底層模塊,二者都應(yīng)該依賴其抽象。
抽象不應(yīng)該依賴細(xì)節(jié),細(xì)節(jié)應(yīng)該依賴抽象。
本末倒置可以減少類與類之間的耦合性,提高系統(tǒng)的穩(wěn)定性,提高代碼的可讀性和可維護(hù)性,降低修改程序造成的風(fēng)險。
實例:
public interface ICourse {
void study();
}
public class JavaCourse implements ICourse{
@Override
public void study() {
System.out.println("學(xué)習(xí)Java");
}
}
public class PythonCourse implements ICourse{
@Override
public void study() {
System.out.println("學(xué)習(xí)Python");
}
}
/**
* 方式一:依賴注入,每次學(xué)習(xí)一個新課程就多創(chuàng)建一個類
*/
public class PersonOne {
public void study(ICourse iCourse){
iCourse.study();
}
public static void main(String[] args) {
PersonOne personOne = new PersonOne();
personOne.study(new JavaCourse());
personOne.study(new PythonCourse());
}
}
/**
* 方式二:構(gòu)造器注入,調(diào)用時每次都要創(chuàng)建實例
*/
public class PersonTwo {
private ICourse iCourse;
public PersonTwo(ICourse iCourse) {
this.iCourse = iCourse;
}
public void study() {
iCourse.study();
}
public static void main(String[] args) {
PersonTwo personTwo = new PersonTwo(new JavaCourse());
personTwo.study();
}
}
/**
* 方式三:Setter方式注入
*/
public class PersonThree {
private ICourse iCourse;
public void setCourse(ICourse iCourse) {
this.iCourse = iCourse;
}
public void study() {
iCourse.study();
}
public static void main(String[] args) {
PersonThree personTwo = new PersonThree();
personTwo.setCourse(new JavaCourse());
personTwo.study();
}
}
3、單一職責(zé)(Simple Responsibility Principle)
不要存在多于一個導(dǎo)致類變更的原因
一個對象應(yīng)該只包含單一的職責(zé),并且該職責(zé)被完整地封裝在一個類中。
/**
* course存在兩種處理邏輯,這個地方修改代碼
*/
public class Course {
public void study(String name){
if("直播".equals(name)){
System.out.println("不能快進(jìn)");
}else {
System.out.println("2xx倍速");
}
}
public static void main(String[] args) {
Course course = new Course();
course.study("直播");
}
}
修改下的代碼,這樣把兩個課程給分開控制。
public class LiveCourse {
public void study(String name){
System.out.println("不能快進(jìn)");
}
}
public class ReplayCourse {
public void study(String name){
System.out.println("2xx倍速");
}
}
public class Test {
public static void main(String[] args) {
LiveCourse liveCourse = new LiveCourse();
liveCourse.study("直播");
ReplayCourse replayCourse = new ReplayCourse();
replayCourse.study("測試");
}
}`在這里插入代碼片`
4、接口隔離原則(Interface Segregation Principle)
用多個專門的接口,而不使用單一的接口,客戶端不應(yīng)該依賴它不需要的接口
- 一個類對一類的依賴應(yīng)該建立在最小的接口上
- 建立單一接口,不要建立龐大的接口
- 盡量細(xì)化接口,接口中的方法盡量少
實例:
public interface Animal {
void eat();
void fly();
void swimming();
}
public class Bird implements Animal{
@Override
public void eat() {
}
@Override
public void fly() {
}
@Override
public void swimming() {
}
}
public class Dag implements Animal{
@Override
public void eat() {
}
@Override
public void fly() {
}
@Override
public void swimming() {
}
}
當(dāng)dog不能飛,鳥兒不能游泳的時候,這個方法就會空,這時候需要根據(jù)動物行為設(shè)計不同的接口
public interface EatAnimal {
void eat();
}
public interface FlyAnimal {
void fly();
}
public interface SwimmingAnimal {
void swimming();
}
public class Dog implements SwimmingAnimal, EatAnimal{
@Override
public void eat() {
}
@Override
public void swimming() {
}
}
5、迪米特法則(Law of demeter LoD)
一個對象應(yīng)該對其他對象保持最少的了解。只和朋友交流,不喝陌生人說話。
出現(xiàn)在成員變量、方法的輸入、輸出參數(shù)中的類都可以稱為成員朋友類,出現(xiàn)在方法體內(nèi)內(nèi)部的類不屬于朋友類。
實例:
public class Course {
}
public class Employee {
public void checkNumOfCourse(List<Course> courseList) {
System.out.println("課程數(shù)量" + courseList.size());
}
}
public class Leader {
public void CommandCheckNumber(Employee employee){
List<Course> courseList = new ArrayList<Course>();
for (int i = 0; i < 20; i++) {
courseList.add(new Course());
}
employee.checkNumOfCourse(courseList);
}
public static void main(String[] args) {
Leader leader = new Leader();
Employee employee = new Employee();
leader.CommandCheckNumber(employee);
}
}
根據(jù)迪米特法則,Leader只想要結(jié)果,不需要和Course有直接的接觸,所以這個地方修改
public class EmployeeCp {
public void checkNumOfCourse() {
List<Course> courseList = new ArrayList<Course>();
for (int i = 0; i < 20; i++) {
courseList.add(new Course());
}
System.out.println("課程數(shù)量" + courseList.size());
}
}
public class LeaderCp {
public void CommandCheckNumber(EmployeeCp employee){
employee.checkNumOfCourse();
}
public static void main(String[] args) {
LeaderCp leader = new LeaderCp();
EmployeeCp employee = new EmployeeCp();
leader.CommandCheckNumber(employee);
}
}
6、里氏替換原則(Liskov Substitution Priciple)
如果針對一個類型為T1的對象O1,都有類型T2的對象O2,使得以T1定義的所有程序P在所有的對象O1都替換成O2時,程序P的行為沒有發(fā)生變化,那么類型T2還是類型T1的子類型。
1)子類可以實現(xiàn)父類的抽象方法,但不能覆蓋父類的非抽象方法
2)子類仲可以增加自己特有的方法
3)當(dāng)子類的方法重載父類的方法時,方法的前置條件(入?yún)ⅲ┮雀割惙椒ǖ妮斎雲(yún)?shù)更寬松
4)當(dāng)子類的方法實現(xiàn)
父類的方法時,方法的后置條件(輸出/返回值)要比父類更嚴(yán)格或相等
優(yōu)點:
1)約束繼承泛濫,開閉原則的一種體現(xiàn)
2)加簽程序的健壯性,同時變更也可以做到好的兼容,提高程序的維護(hù)性、擴(kuò)展性,降低需求變更時的風(fēng)險
實例:
public class Rectangle {
private Long height;
private Long width;
public Long getHeight() {
return height;
}
public Long getWidth() {
return width;
}
public void setHeight(Long height) {
this.height = height;
}
public void setWidth(Long width) {
this.width = width;
}
}
public class Square extends Rectangle {
private Long length;
public Long getLength() {
return length;
}
public void setLength(Long length) {
this.length = length;
}
@Override
public Long getHeight() {
return getLength();
}
@Override
public void setHeight(Long height) {
setLength(height);
}
@Override
public Long getWidth() {
return getLength();
}
@Override
public void setWidth(Long width) {
setLength(width);
}
}
public class Test {
public static void resize(Rectangle rectangle){
while (rectangle.getWidth() >= rectangle.getHeight()){
rectangle.setHeight(rectangle.getHeight()+1);
System.out.printf("width: %s, height:%s", rectangle.getWidth(), rectangle.getHeight());
}
System.out.printf("width: %s, height:%s", rectangle.getWidth(), rectangle.getHeight());
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setWidth(20L);
rectangle.setHeight(10L);
resize(rectangle);
//死循環(huán)
Square square = new Square();
square.setLength(10L);
resize(square);
}
}
當(dāng)是正方形的時候,陷入死循環(huán),違背里氏替換原則,父類替換成子類后結(jié)果不是預(yù)期。
修改代碼,創(chuàng)建一個抽象四邊形
public interface QuadRectangle {
Long getWidth();
Long getHeight();
}
public class RectangleCp implements QuadRectangle{
private Long height;
private Long width;
public Long getHeight() {
return height;
}
public Long getWidth() {
return width;
}
public void setHeight(Long height) {
this.height = height;
}
public void setWidth(Long width) {
this.width = width;
}
}
public class SquareCp implements QuadRectangle {
private Long length;
public Long getLength() {
return length;
}
public void setLength(Long length) {
this.length = length;
}
@Override
public Long getHeight() {
return getLength();
}
@Override
public Long getWidth() {
return getLength();
}
}
7、合成復(fù)用原則(Composite Reuse Principle)
盡量使用對象組合(has-a)/聚合(contain-a),而不是繼承達(dá)到軟件復(fù)用的目的。
繼承叫做“白箱復(fù)用”,把所有的實現(xiàn)細(xì)節(jié)暴露給子類
組合/聚合稱為“黑箱復(fù)用”,對類以外的對象是無法獲取到實現(xiàn)細(xì)節(jié)的
實例:
public class DBConnection {
public String getConnection() {
return "MySql連接";
}
}
public class ProductDao {
private DBConnection dbConnection;
public void setDbConnection(DBConnection dbConnection){
this.dbConnection = dbConnection;
}
public void addProduct(){
String conn = dbConnection.getConnection();
System.out.println("創(chuàng)建商品");
}
}
如果這時候不只是mysql還有其他類型的數(shù)據(jù)庫,違反開閉原則
修改代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-606819.html
public abstract class DBConnectionCp {
public abstract String getConnection();
}
public class MysqlConnection extends DBConnection{
@Override
public String getConnection() {
return "mysql";
}
}
public class OracleConnection extends DBConnection{
@Override
public String getConnection() {
return "Oracle";
}
}
到了這里,關(guān)于七大設(shè)計模式原則的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!