标签:实例 应该 break bre int str 创建 模式 继承
简单(静态)工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例。
package factory;
//雷锋接口,包含扫地、洗衣、买米的方法
public interface LeiFeng {
void sweep();
void wash();
void buyRice();
}
实现类一:大学生雷锋
package factory;
/**
*大学生雷锋
*/
public class UnderGraduate implements LeiFeng {
@Override
public void sweep() {
System.out.println("大学生雷锋帮忙扫地");
}
@Override
public void wash() {
System.out.println("大学生雷锋帮忙洗衣");
}
@Override
public void buyRice() {
System.out.println("大学生雷锋帮忙买米");
}
}
实现类二:社区志愿者
package factory;
public class Volunteer implements LeiFeng {
@Override
public void sweep() {
System.out.println("社区志愿者帮忙扫地");
}
@Override
public void wash() {
System.out.println("社区志愿者帮忙洗衣");
}
@Override
public void buyRice() {
System.out.println("社区志愿者帮忙买米");
}
}
简单工厂类:
package factory;
public class SimplyFactory {
public static final String UNDERGTADUATE = "1";
public static final String VOLUNTEER = "2";
public static LeiFeng getLeiFeng(String name){
LeiFeng leifeng = null;
switch (name) {
case (UNDERGTADUATE):
leifeng = new UnderGraduate();
break;
case(VOLUNTEER):
leifeng = new Volunteer();
break;
}
return leifeng;
}
}
测试类:
package factory;
public class Test {
public static void main(String[] args) {
LeiFeng leifeng1 = SimplyFactory.getLeiFeng(SimplyFactory.UNDERGTADUATE);
leifeng1.buyRice();
LeiFeng leifeng2 = SimplyFactory.getLeiFeng(SimplyFactory.VOLUNTEER);
leifeng2.buyRice();
}
}
例子:LeiFeng,UnderGraduate,Volunteer这三个类代码就不粘贴了。
//工厂接口,只包含一个方法,创造雷锋
public interface IFactory {
LeiFeng createLeiFeng();
}
大学生雷锋工厂类:
public class UnderGraduateFactory implements IFactory {
@Override
public LeiFeng createLeiFeng() {
return new UnderGraduate();
}
}
社区志愿者工厂类:
public class VolunteerFactory implements IFactory {
@Override
public LeiFeng createLeiFeng() {
return new Volunteer();
}
}
测试类:
public class Test {
public static void main(String[] args) {
IFactory iFactory = new UnderGraduateFactory();//改成VolunteerFactory,就成了社区志愿者
LeiFeng leifeng = iFactory.createLeiFeng();
leifeng.sweep();
}
}
结果:
工厂模式优缺点:
参考书籍:《大话设计模式》第八章 雷锋依然在人间-工厂方法模式
标签:实例 应该 break bre int str 创建 模式 继承
原文地址:https://www.cnblogs.com/caozx/p/9089899.html