工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类。(解决了简单工厂模式违反OCP的问题)
代码
using System;
using System.Collections.Generic;
using System.Text;
namespace Factory
{
class Program
{
static void Main(string[] args)
{
Ifactory factory = new Undergraduate();
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
Console.ReadLine();
}
}
public class LeiFeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
Console.WriteLine("买米");
}
}
//雷锋工厂
public interface Ifactory
{
LeiFeng CreateLeiFeng();
}
public class Undergraduate:LeiFeng,Ifactory //类放在前 接口放在后。
{
public LeiFeng CreateLeiFeng()
{
return new Undergraduate();
}
}
public class Volunteer :LeiFeng,Ifactory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace Factory
{
class Program
{
static void Main(string[] args)
{
Ifactory factory = new Undergraduate();
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
Console.ReadLine();
}
}
public class LeiFeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
Console.WriteLine("买米");
}
}
//雷锋工厂
public interface Ifactory
{
LeiFeng CreateLeiFeng();
}
public class Undergraduate:LeiFeng,Ifactory //类放在前 接口放在后。
{
public LeiFeng CreateLeiFeng()
{
return new Undergraduate();
}
}
public class Volunteer :LeiFeng,Ifactory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
}