泡泡

              宠辱不惊-闲看庭前花开花落
                           去留无意-漫观天外云展云舒
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

04)Factory Method

Posted on 2007-09-15 15:38  AlanPaoPao  阅读(150)  评论(0)    收藏  举报
    工厂方法模式的目的是: 使一个类的实例化延迟到其子类。
    实例代码:
abstract class Food  //定义抽象食物类
{
}

class Apple : Food //苹果类
{
  
public override string ToString()
  
{
    
return "This is apple";
  }

}

class Banana : Food //香蕉类
{
  
public override string ToString()
  
{
    
return "This is banana";
  }

}

class Peach : Food //桃子类
{
  
public override string ToString()
  
{
    
return "This is peach";
  }

}

class Coke : Food //可乐类
{
  
public override string ToString()
  
{
    
return "This is coke";
  }

}

class Coffee : Food //咖啡类
{
  
public override string ToString()
  
{
    
return "This is coffee";
  }

}

class Hamburger : Food //汉堡包类
{
  
public override string ToString()
  
{
    
return "This is hamburger";
  }

}

class Noodle : Food //面条类
{
  
public override string ToString()
  
{
    
return "This is noodle";
  }

}

class Meal : Food //米饭类
{
  
public override string ToString()
  
{
    
return "This is meal";
  }

}

abstract class Eat  //食用类
{
  
private List<Food> _foods = new List<Food>();  //食物清单
  public Eat()
  
{
    
this.CreateFoods();
  }

  
public List<Food> Foods
  
{
    
get return this._foods; }
  }

  
public abstract void CreateFoods();
}

class Fruit : Eat  //水果类
{
  
public override void CreateFoods()
  
{
    Foods.Add(
new Apple());
    Foods.Add(
new Banana());
    Foods.Add(
new Peach());
  }

  
public override string ToString()
  
{
    
return "水果";
  }

}

class Drink : Eat  //饮料类
{
  
public override void CreateFoods()
  
{
    Foods.Add(
new Coke());
    Foods.Add(
new Coffee());
  }

  
public override string ToString()
  
{
    
return "饮料";
  }

}

class StapleFood : Eat  //主食类
{
  
public override void CreateFoods()
  
{
    Foods.Add(
new Hamburger());
    Foods.Add(
new Noodle());
    Foods.Add(
new Meal());
  }

  
public override string ToString()
  
{
    
return "主食";
  }

}

class MainApp //测试
{
  
static void Main()
  
{
    Eat[] eats 
= new Eat[3];
    eats[
0= new Fruit();
    eats[
1= new Drink();
    eats[
2= new StapleFood();
    
foreach (Eat eat in eats)
    
{
      Console.WriteLine(
"小胖开始吃: " + eat.ToString() + "");
      
foreach (Food food in eat.Foods)
      
{
        Console.WriteLine(
" " + food.ToString());
      }

    }

    Console.WriteLine(
"小胖吃饱咯:)");
    Console.Read();
  }

}