类结构图:
//工厂方法模式,工厂接口
public interface Factory {
LeiFeng createLeiFengFactory();
}
//雷锋
public interface LeiFeng {
void sweep();//扫地
void wash();//洗衣
void buyrice();//做饭
}
//使用简单工厂
public class SimpleFactory {
public static LeiFeng createLeiFeng(String type){
if("大学生".equals(type)){
return new Student();
}else if("志愿者".equals(type)){
return new Valuator();
}
return null;
}
}
//学做雷锋的大学生
public class Student implements LeiFeng{
public void buyrice() {
System.out.println("大学生做饭");
}
public void sweep() {
// TODO Auto-generated method stub
System.out.println("大学生扫地");
}
public void wash() {
// TODO Auto-generated method stub
System.out.println("大学生洗衣");
}
}
//学做雷锋的志愿者
public class Valuator implements LeiFeng{
public void buyrice() {
System.out.println("志愿者做饭");
}
public void sweep() {
// TODO Auto-generated method stub
System.out.println("志愿者扫地");
}
public void wash() {
// TODO Auto-generated method stub
System.out.println("志愿者洗衣");
}
}
//学生工厂
public class StudentFactory implements Factory{
public LeiFeng createLeiFengFactory() {
return new Student();
}
}
//志愿者工厂
public class ValuatorFactory implements Factory{
public LeiFeng createLeiFengFactory() {
return new Valuator();
}
}
public static void main(String[] args) {
//第一种方式:传统方式,直接new
//这个时候如果要把大学生给改成志愿者的话需要把三个类都给替换掉
//如果大学生多的话那替换就会变得很麻烦,而且代码不美观
LeiFeng f1=new Student();
f1.wash();
LeiFeng f2=new Student();
f2.sweep();
LeiFeng f3=new Student();
f3.buyrice();
//第二种方式,简单工厂模式
//这个时候你就会发现,这里有两句重复的代码,如果要改成
//志愿者,也要修改两次,如果数量多的话那修改也多
LeiFeng f11=SimpleFactory.createLeiFeng("大学生");
f11.buyrice();
LeiFeng f22=SimpleFactory.createLeiFeng("大学生");
f22.wash();
//第三种方式,使用工厂方法模式
Factory fac=new StudentFactory();//像这里的话只需要替换这个工厂类名即可
LeiFeng f4=fac.createLeiFengFactory();
f4.buyrice();
LeiFeng f5=fac.createLeiFengFactory();
f5.wash();
}
}