創建型模式之抽象工廠(轉)

来源:互联网 发布:sql语音中删除表命令 编辑:程序博客网 时间:2024/05/21 07:33
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Walter.K.Wang.Abstract
{
    
public abstract class ContinentFactory
    
{
        
public abstract Herbivore CreateHerbivore();
        
public abstract Carnivore CreateCarnivore();
    }


    
public class AfricaFactory : ContinentFactory
    
{
        
public override Herbivore CreateHerbivore()
        
{
            
return new Wildebeest();
        }

        
public override Carnivore CreateCarnivore()
        
{
            
return new Lion();
        }

    }

    
public class AmericaFactory : ContinentFactory
    
{
        
public override Herbivore CreateHerbivore()
        
{
            
return new Bison();
        }


        
public override Carnivore CreateCarnivore()
        
{
            
return new Wolf();
        }

    }

    
public abstract class Herbivore
    
{
    }

    
public abstract class Carnivore
    
{
        
public abstract void Eat(Herbivore h);
    }

    
class Wildebeest : Herbivore
    
{
    }

    
class Lion : Carnivore
    
{
        
public override void Eat(Herbivore h)
        
{
            MessageBox.Show(
this.GetType().Name + " eats " + h.GetType().Name, "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }

    
class Bison : Herbivore
    
{
    }

    
class Wolf : Carnivore
    
{
        
public override void Eat(Herbivore h)
        
{
            MessageBox.Show(
this.GetType().Name + " eats " + h.GetType().Name, "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }

    
public class AnimalWorld
    
{
        
private Herbivore herbivore;
        
private Carnivore carnivore;
        
public AnimalWorld(ContinentFactory factory)
        
{
            carnivore 
= factory.CreateCarnivore();
            herbivore 
= factory.CreateHerbivore();
        }

        
public void RunFoodChain()
        
{
            carnivore.Eat(herbivore);
        }

    }

}

 

 

        private void 抽象工廠ToolStripMenuItem_Click(object sender, EventArgs e)
        
{
            ContinentFactory africa 
= new AfricaFactory();
            AnimalWorld world 
= new AnimalWorld(africa);
            world.RunFoodChain();

            ContinentFactory america 
= new AmericaFactory();
            world 
= new AnimalWorld(america);
            world.RunFoodChain();
        }
原创粉丝点击