Using a Class Factory to Create Objects— Single Factory




using System;
using System.Collections.Generic;
using System.Text;

namespace SampleFactoryClass
{
public interface IApparel // Interface representing product
{

string ShowMe();

bool Knit // Property to indicate if Knit

{ get; }

}

public class SportsShirt : IApparel
{

public string ShowMe()
{

return ("Sports Shirt");

}

public bool Knit

{ get { return true; } }

}

public class DressShirt : IApparel
{

public string ShowMe()
{

return ("Dress Shirt");

}

public bool Knit

{ get { return false; } }

}

// Factory to return instances of apparel classes

public class ApparelFactory
{

public IApparel CreateApparel(string apptype)
{

switch (apptype)
{

case "MDRSHIRT":

return new DressShirt();

case "MSPSHIRT":

return new SportsShirt();

}

return null;

}
public static void Main()
{

ApparelFactory factory = new ApparelFactory();

IApparel ob1 = factory.CreateApparel("MDRSHIRT");

IApparel ob2 = factory.CreateApparel("MSPSHIRT");

string shirtType = ob1.ShowMe(); // Returns "Dress Shirt"
Console.WriteLine(shirtType);
Console.Read();





}

}


}

No comments:

Post a Comment