设计模式原则之:开闭原则原则
类似于做一个多支付的业务,提供一个service来进行支付、查询操作,具体的实现类如:WeChat、AliPay等实现service服务,来进行服务的调用,如果后续增加Paypal支付,则由提供方实现service即可使用方无需动代码
引发开闭原则的实例
/**
* @description: 引发开闭原则的示例
* @author: abel.he
* @date: 2023-08-03
**/
public class Test {
public static void main(String[] args) {
Print print = new Print();
print.print(new Son1());
print.print(new Son2());
// 如果增加3 需要新增一个类(提供方) 且 在使用的过程中增加判断(使用方) 不符合开闭原则(ocp) 且后续处理的越多会越麻烦
}
}
class Parent {
int type;
}
class Son1 extends Parent {
public Son1() {
super.type = 1;
}
}
class Son2 extends Parent {
public Son2() {
super.type = 2;
}
}
class Print {
public void print(Parent parent) {
// 第一种判断写法
if (parent.type == 1) {
System.out.println("son1 打印了数据");
} else if (parent.type == 2) {
System.out.println("son2 打印了数据");
}
// 第二种判断写法
switch (parent.type){
case 1 -> System.out.println("son1 打印了数据");
case 2 -> System.out.println("son2 打印了数据");
}
}
}
分析上面代码
- 比较好理解,简单已操作
- 缺点是违反了设计模式开闭(ocp)原则,即对扩展开放(提供方),对修改关闭(使用方)。即当我们给类增加新功能的时候,尽量不修改代码,或者尽量少修改代码
开闭原则进行优化
/**
* @description: 开闭原则实现
* @author: abel.he
* @date: 2023-08-03
**/
public class Test {
public static void main(String[] args) {
Print print = new Print();
print.print(new Son1());
print.print(new Son2());
// 如果想实现其他的 则可以使用Son3实现Person 来完成功能的增加
}
}
abstract class Person {
int type;
abstract void print();
}
class Son1 extends Person {
public Son1() {
super.type = 1;
}
@Override
void print() {
System.out.println("son1 打印");
}
}
class Son2 extends Person {
public Son2() {
super.type = 2;
}
@Override
void print() {
System.out.println("son2 打印");
}
}
class Print {
public void print(Person person) {
person.print();
}
}

浙公网安备 33010602011771号