工厂模式
不解释,直接上代码
// 雷锋工厂
interface IFactory {
LeiFeng CreateLeiFeng();
}
// 学雷锋的大学生工厂
class UndergraduateFactory : IFactory {
public LeiFeng CreateLeiFeng() {
return new Undergraduate();
}
}
// 社区志愿者工厂
class VolunteerFactory : IFactory {
public LeiFeng CreateLeiFeng() {
return new Volunteer();
}
}
//客户端调用
IFactory factory = new UndergraduateFactory();
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
student.Wash();
与简单工厂的区别:
简单工厂写法如下:
class SimpleFactory {
public static LeiFeng CreateLeiFeng(string type) {
LeiFeng result = null;
switch(type) {
case "学雷锋的大学生":
result = new Undergraduate();
break;
case "社区志愿者":
result = new Volunteer();
break;
}
return result;
}
}
// 客户端调用
LeiFeng studentA = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentA.BuyRice();
LeiFeng studentB = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentB.Sweep();
LeiFeng studentC = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentC.Wash();