大话设计模式-工厂方法模式
/**
* 工厂方法
*/
public interface IFactory {
LeiFeng createLeiFeng();
}
/**
* 雷锋
*/
public class LeiFeng {
public void sweep() {
System.out.println("扫地");
}
public void wash() {
System.out.println("洗衣");
}
public void buyRice() {
System.out.println("买米");
}
}
/**
* 学雷锋的大学生
*/
public class Undergraduate extends LeiFeng {
}
/**
* 工厂方法生成学雷锋的大学生
*/
public class UndergraduateFactory implements IFactory {
@Override
public LeiFeng createLeiFeng() {
return new Undergraduate();
}
}
/**
* 学雷锋的社区志愿者
*/
public class Volunteer extends LeiFeng {
}
/**
* 工厂方法生成学雷锋的社区志愿者
*/
public class VolunteerFactory implements IFactory {
@Override
public LeiFeng createLeiFeng() {
return new Volunteer();
}
}
如果使用简单工厂实现:
/**
* 简单工厂
*/
public class SimpleFactory {
public static LeiFeng createLeiFeng(String type) {
LeiFeng result = null;
switch (type) {
case "学雷锋的大学生":
result = new Undergraduate();
break;
case "社区志愿者":
result = new Undergraduate();
break;
}
return result;
}
}
Main:
public class Main {
public static void main(String[] args) {
// 简单工厂实现
LeiFeng student1 = SimpleFactory.createLeiFeng("学雷锋的大学生");
student1.sweep();
// 工厂方法实现
IFactory factory = new UndergraduateFactory();
LeiFeng student2 = factory.createLeiFeng();
student2.sweep();
}
}