ITeye博客

设计模式示例三 Abstract Factory(抽象工厂)

netxdiy · 2007-07-13 16:58 · Markdown

<script type="text/javascript"><!-- google_ad_client = "pub-0241434510974184"; /* auto-http.cn 右边 ,468x60 */ google_ad_slot = "0902256228"; google_ad_width = 468; google_ad_height = 60; // --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

示例名称:家庭合唱比赛
示例说明:定义抽象的父亲(AbstractFather)、母亲(Abstractmother)和孩子**(AbstractChild)及抽象行为Sing。定义抽象的家庭(AbstractFamily),包含父亲、母亲和孩子行为有初始化成员(ConstructMember),准备(抽象的GetReadyToSing),合唱(Tutti),谢幕(抽象的Thank)。定义抽象的家庭工厂负责创建父亲、母亲和孩子。
定义家庭A(FamilyA)、父亲A(FatherA)、母亲A(MotherA)、和孩子A(ChildA)及家庭工厂A(FactoryA)分别继承自家庭、父亲、母亲、孩子和家庭工厂。
示例类图:

关键部分说明

家庭、

父亲、

母亲、

孩子和

家庭工厂

//抽象的家庭
abstractclassAbstractFamily
...{
//家庭成员
protectedAbstractFatherfarther;
protectedAbstractmothermother;
protectedAbstractChildchild;

//创建家庭成员
publicvoidConstructMember(AbstractFamilyFactoryfactory)
...{
farther=factory.CreateFather();
mother=factory.CreateMother();
child=factory.CreateChild();
}

//合唱准备工作
abstractpublicvoidGetReadyToSing();
//谢幕
abstractpublicvoidThanks();

//合唱
publicvoidTutti()
...{
if(farther!=null)farther.Sing();
if(mother!=null)mother.Sing();
if(child!=null)child.Sing();
}
}

//抽象父亲
abstractclassAbstractFather
...{
abstractpublicvoidSing();
}

//抽象母亲
abstractclassAbstractmother
...{
abstractpublicvoidSing();
}

//抽象孩子
abstractclassAbstractChild
...{
abstractpublicvoidSing();
}

//抽象家庭工厂
abstractclassAbstractFamilyFactory
...{
abstractpublicAbstractFatherCreateFather();
abstractpublicAbstractmotherCreateMother();
abstractpublicAbstractChildCreateChild();
}

关键在于这个抽象的家庭(AbstractFamily),它的行为合唱(Tutti)包装了基于通过抽象的家庭工厂(AbstractFamilyFactory)创建的家庭成员的行为。

家庭A

classFamilyA:AbstractFamily
...{
publicFactoryAfactory=newFactoryA();

publicoverridevoidGetReadyToSing()
...{
Console.WriteLine("我们是幸运家庭A,我们已经做好了上台的准备!");
}

publicoverridevoidThanks()
...{
Console.WriteLine("我们是幸运家庭A,我们的演出结束,谢谢大家!");
}
}

classFatherA:AbstractFather
...{
publicoverridevoidSing()
...{
Console.WriteLine("我是父亲,我唱男高音!");
}
}

classMotherA:Abstractmother
...{
publicoverridevoidSing()
...{
Console.WriteLine("我是母亲,我唱民歌");
}
}

classChildA:AbstractChild
...{
publicoverridevoidSing()
...{
Console.WriteLine("我是孩子,我唱儿童歌曲!");
}
}

classFactoryA:AbstractFamilyFactory
...{
publicoverrideAbstractFatherCreateFather()
...{
returnnewFatherA();
}
publicoverrideAbstractmotherCreateMother()
...{
returnnewMotherA();
}
publicoverrideAbstractChildCreateChild()
...{
returnnewChildA();
}
}

通过对对应的抽象类的继承实现了和抽象类相同的创建、组织和表示。

调用及运行结果

FamilyAfamily=newFamilyA();
family.ConstructMember(family.factory);
family.GetReadyToSing();
family.Tutti();
family.Thanks();

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。