namespace Test_IOC和工厂
{
interface 可以吃的东西
{
void 被吃();
}
class 创造苹果 : 可以吃的东西 //种苹果
{
public void 被吃()
{
//System.out.println("delicious 苹果");
}
}
class 创造蔬菜 : 可以吃的东西 //种橘子
{
public void 被吃()
{
//System.out.println("delicious orange");
}
}
class 冰箱 //静态工厂
{
//静态工厂
static public 可以吃的东西 拿吃的(string type)
{
if (type == "fruit")
return new 创造苹果();
else
{
return new 创造蔬菜();
}
}
}
//原始方法
class ChildA
{
public void 想吃东西()
{
var 苹果 = new 创造苹果();//自己种苹果
苹果.被吃();//再来吃
//如果哪天想换蔬菜,就要重新New新的蔬菜
}
}
//使用工厂
class ChildB
{
public void 想吃东西()
{
可以吃的东西 eatble = 冰箱.拿吃的("fruit");//Fridge.getEatable 小孩去冰箱拿吃的(工厂),不需要自己种水果
eatble.被吃();//是吃冰箱拿到的某个水果。
//如果哪天想换橘子,就可以自己去冰箱拿(修改getEatable入参)
}
}
//使用IOC方法。
class ChildC
{
private 可以吃的东西 eatble;
//构造注入
public ChildC(可以吃的东西 eatble)//(容器),吃什么由外部帮你拿
{
this.eatble = eatble;
}
public void wantToEat()
{
this.eatble.被吃();//不要去冰箱,只要专注与吃这个动作。
}
}
}