作为一个大学生需要经常参加学雷锋,同时还有社区志愿者等

我们需要考虑的

  • 满足开放-封闭原则

使用简单工厂模式实现

雷锋类

1
2
3
4
5
6
7
8
9
10
11
public class LeiFeng {
public void sweep() {
System.out.println("扫地");
}
public void wash() {
System.out.println("洗衣");
}
public void buy() {
System.out.println("买东西");
}
}

新雷锋类

1
public class Student extends LeiFeng {}
1
public class VolunteerA extends LeiFeng {}

雷锋工厂类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class LeiFengFactory {
public LeiFeng createXueLeiFeng(String type) {
switch (type) {
case "学生" : {
return new Student();
}
case "志愿者A" : {
return new VolunteerA();
}
}
return null;
}
}

客户端

1
2
3
4
5
6
public static void main(String[] args) {
String type = "学生";
LeiFengFactory leiFengFactory = new LeiFengFactory();
LeiFeng studentA = leiFengFactory.createXueLeiFeng("学生");
LeiFeng studentB = leiFengFactory.createXueLeiFeng("学生");
}

工厂方法模式UML图

avatar

工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。
工厂方法使得一个类的实例化延迟到其子类。

使用工厂方法模式实现

抽象雷锋工厂接口

1
2
3
public interface ILeiFengFactory {
public LeiFeng createXueLeiFeng();
}

实现抽象工厂接口的具体工厂

1
2
3
4
5
public class StudentLeiFengFactory implements ILeiFengFactory{
public LeiFeng createXueLeiFeng() {
return new Student();
}
}
1
2
3
4
5
6
public class VolunteerLeiFengFactory implements ILeiFengFactory {
@Override
public LeiFeng createXueLeiFeng() {
return new VolunteerA();
}
}

客户端

1
2
3
4
5
public static void main(String[] args) {
ILeiFengFactory studentLeiFengFactory = new StudentLeiFengFactory();
LeiFeng leiFeng1 = studentLeiFengFactory.createXueLeiFeng();
leiFeng1.buy();
}

工厂方法模式的优势

  1. 相比简单工厂模式,在增加新的“学雷锋”时无需修改工厂类类,满足开放-封闭原则
  2. 用户只需要关心所需产品对应的工厂,无需关心创建细节,甚至无需知道具体产品类名

工厂方法模式的缺点

  1. 添加一个新的产品,系统中类的个数增加,导致增加了系统的复杂性,有更多的类需要编译和运行,会增加系统性能的开销
  2. 引入抽象层,增加了系统的抽象性和理解难度

本文部分内容改编于程杰老师的《大话设计模式》