The Example here has an implementation of an Abstract Factory as an Interface
IAVDevice
that has methods that can create an Audio object and a Video object.
The client Codes against
IAVDevice
and getsIAudio
and IVideo
interfaces.
Passing "cd" in the command line creates a family of cd objects (Audio and Video) and "dvd" creates a family of dvd objects (Audio and Video).
The client doesn’t care which object (cd audio video or dvd audio video),
IAVDevice
interface returns as it codes against IAudio
andIVideo
interface.
C# Implementation of Abstract Factory design pattern:
using System; public interface IAVDevice { IAudio GetAudio(); IVideo GetVideo(); } public interface IVideo { string GetPictureQuality(); } public interface IAudio { string GetSoundQuality(); } class CCd:IAVDevice { public IAudio GetAudio() { return new CCdAudio(); } public IVideo GetVideo() { return new CCdVideo(); } } class CDvd:IAVDevice { public IAudio GetAudio() { return new CDvdAudio(); } public IVideo GetVideo() { return new CDvdVideo(); } } class CCdAudio:IAudio { public string GetSoundQuality() { return "CD Audio is better then DVD Audio"; } } class CCdVideo:IVideo { public string GetPictureQuality() { return "CD video quality is not as good as DVD"; } } class CDvdAudio:IAudio { public string GetSoundQuality() { return "DVD Audio is not as good as CD Audio"; } } class CDvdVideo:IVideo { public string GetPictureQuality() { return "DVD video quality is better then CD"; } } class CAVMaker { public IAVDevice AVMake(string xWhat) { switch (xWhat.ToLower()) { case "cd": return new CCd(); case "dvd": return new CDvd(); default: return new CCd(); } } } public class AbstractFactory { static void Main(string[] args) { CAVMaker objFactMaker = new CAVMaker(); IAVDevice objFact; IAudio objAudio; IVideo objVideo; string strWhat; strWhat = args[0]; objFact = objFactMaker.AVMake(strWhat); objAudio = objFact.GetAudio(); objVideo = objFact.GetVideo(); Console.WriteLine(objAudio.GetSoundQuality()); Console.WriteLine(objVideo.GetPictureQuality()); } }
Không có nhận xét nào:
Đăng nhận xét