berikut adalah contoh program menggunakan bahasa pemrograman CSharp (C#) :
using System; using System.Collections.Generic; using System.Text; namespace AbstractFactoryDemo { class Program { static void Main(string[] args) { PhoneTypeChecker checker = new PhoneTypeChecker(MANUFACTURERS.SAMSUNG); checker.CheckProducts(); Console.ReadLine(); checker = new PhoneTypeChecker(MANUFACTURERS.HTC); checker.CheckProducts(); Console.ReadLine(); checker = new PhoneTypeChecker(MANUFACTURERS.NOKIA); checker.CheckProducts(); Console.Read(); } } interface IPhoneFactory { ISmart GetSmart(); IDumb GetDumb(); } class SamsungFactory : IPhoneFactory { public ISmart GetSmart() { return new GalaxyS2(); } public IDumb GetDumb() { return new Primo(); } } class HTCFactory : IPhoneFactory { public ISmart GetSmart() { return new Titan(); } public IDumb GetDumb() { return new Genie(); } } class NokiaFactory : IPhoneFactory { public ISmart GetSmart() { return new Lumia(); } public IDumb GetDumb() { return new Asha(); } } class Lumia : ISmart { public string Name() { return "Lumia"; } } class Asha : IDumb { public string Name() { return "Asha"; } } interface ISmart { string Name(); } class GalaxyS2 : ISmart { public string Name() { return "GalaxyS2"; } } class Primo : IDumb { public string Name() { return "Blue"; } } interface IDumb { string Name(); } class Titan : ISmart { public string Name() { return "Titan"; } } class Genie : IDumb { public string Name() { return "Genie"; } } enum MANUFACTURERS { SAMSUNG, HTC, NOKIA } class PhoneTypeChecker { IPhoneFactory factory; MANUFACTURERS manu; public PhoneTypeChecker(MANUFACTURERS m) { manu = m; } public void CheckProducts() { switch (manu) { case MANUFACTURERS.SAMSUNG: factory = new SamsungFactory(); break; case MANUFACTURERS.HTC: factory = new HTCFactory(); break; case MANUFACTURERS.NOKIA: factory = new NokiaFactory(); break; } Console.WriteLine(manu.ToString() + ":\nSmart Phone: " + factory.GetSmart().Name() + "\nDumb Phone: " + factory.GetDumb().Name()); } } }
0 komentar:
Posting Komentar