public class Ball
{
public string Play(string ballType)
{
return “Play+"ballType"”;
}
}
public class FootBall: Ball
{
public override string Play(string ballType)
{
return “Play+ballType”;
}
}
public class BasketBall: Ball
{
public override string Play(string ballType)
{
return “Play+ballType”;
}
}
创建简单工厂public static Bal CreatObject(string operate)
{
Operation oper = null;
switch (operate)
{
case "FootBall":
oper = new FootBall();
break;
case "BasketBall":
oper = new OperationSub();
break;
case "*":
oper = new BasketBall();
break;
default:
break;
}
return oper;
}
调用工厂:
Ball b=CreatObject.Play("FootBall");
工厂模式其实就是不需要你做实例化类的操作,已经有了一个实例化类的处理。
本例中有一个Ball的类,一个抽象方法Play,然后2个子类,足球,篮球。Play()不知道玩的是什么球类,但是你传入FootBall时,因为有了CreatObject这个方法,他自己去匹配需要实例化的对象是谁,所以Ball a=CreatObject.Play("FootBall")就实现了。 |