首先先说简单工厂模式:一个父类拥有一个或者多个子类。父类可以通过多态,实例化多个子类。
代码如下
package effective.company;
public class LeiFeng {
public void Sweep(){
System.out.println("扫地。。。");
}
public void Wash(){
System.out.println("洗衣。。");
}
public void BuyRice(){
System.out.println("买米。。");
}
public static void main(String[] args) {
IFactory factory = new VolunteerFactory();
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
student.Wash();
}
}
package effective.company;
public class Volunteer extends LeiFeng {
public void Sweep(){
System.out.println("志愿者扫地。。。");
}
public void Wash(){
System.out.println("志愿者洗衣。。");
}
public void BuyRice(){
System.out.println("志愿者买米。。");
}
}
package effective.company;
public class Undergraduate extends LeiFeng {
public void Sweep(){
System.out.println("学生扫地。。。");
}
public void Wash(){
System.out.println("学生洗衣。。");
}
public void BuyRice(){
System.out.println("学生买米。。");
}
}
客户端调用的时候代码如下:
package effective.company;
public class SimpleFactory {
public static LeiFeng CreateLeiFeng(String type) {
LeiFeng lf = null;
switch (type) {
case "大学生":
lf = new Undergraduate();
break;
case "志愿者":
lf = new Volunteer();
break;
}
return lf;
}
public static void main(String[] args) {
LeiFeng s1 = SimpleFactory.CreateLeiFeng("大学生");
s1.BuyRice();
LeiFeng s2 = SimpleFactory.CreateLeiFeng("大学生");
s2.Wash();
LeiFeng s3 = SimpleFactory.CreateLeiFeng("大学生");
s3.BuyRice();
}}
从如上代码可以知:简单工厂模式在实例化 调用对应方法的时候产生过多的重复代码。如果修改大学生为志愿者则修改三处地方;
以下是工厂模式:
package effective.company;
public interface IFactory {
LeiFeng CreateLeiFeng();
}
package effective.company;
public class UndergraduateFactory implements IFactory{
@Override
public LeiFeng CreateLeiFeng() {
// TODO Auto-generated method stub
return new Undergraduate();
}
}
package effective.company;
public class VolunteerFactory implements IFactory {
@Override
public LeiFeng CreateLeiFeng() {
// TODO Auto-generated method stub
return new Volunteer();
}
}
IFactory factory = new VolunteerFactory();//只需修改此处即可
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
student.Wash();