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

本文通过C#代码示例展示了抽象工厂模式的应用,该模式提供了一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。示例中非洲和美洲工厂分别创建各自大陆特有的食草动物和食肉动物。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值