There is a factory interface that declares what this factory is supposed to produce. Then, there is an implementation, which is the way how to produce. In the example below, I am using a factory that produces watches of types Elegant and Sporty. Hence I have an factory interface - IWatchFactory. This interface is implemented as WatchFactory. Now the watches are different implementation of IWatch interface.
Here is the C# implementation:
/// <summary>
/// Interface for common watch type
/// </summary>
public interface IWatch
{
string GetType();
}
/// <summary>
/// Elegant class implementation of IWatch interface
/// </summary>
public class ElegantWatch : IWatch
{
public string GetType()
{
return "Elegant";
}
}
/// <summary>
/// Sporty class implementation of IWatch interface.
/// </summary>
public class SportyWatch : IWatch
{
public string GetType()
{
return "Sporty";
}
}
/// <summary>
/// Factory interface to generate watches
/// </summary>
public interface IWatchFactory
{
IWatch GetElegantWatch();
IWatch GetSportyWatch();
}
/// <summary>
/// Watch factory implementation of IWatchFactory interface
/// </summary>
public class WatchFactory : IWatchFactory
{
public IWatch GetElegantWatch()
{
return new ElegantWatch();
}
public IWatch GetSportyWatch()
{
return new SportyWatch();
}
}
Here is how to use it:
IWatchFactory watchFactory = new WatchFactory();
IWatch watch = watchFactory.GetElegantWatch();
System.Diagnostics.Debug.WriteLine(watch.GetType());
watch = watchFactory.GetSportyWatch();
System.Diagnostics.Debug.WriteLine(watch.GetType());
Here is the C# implementation:
/// <summary>
/// Interface for common watch type
/// </summary>
public interface IWatch
{
string GetType();
}
/// <summary>
/// Elegant class implementation of IWatch interface
/// </summary>
public class ElegantWatch : IWatch
{
public string GetType()
{
return "Elegant";
}
}
/// <summary>
/// Sporty class implementation of IWatch interface.
/// </summary>
public class SportyWatch : IWatch
{
public string GetType()
{
return "Sporty";
}
}
/// <summary>
/// Factory interface to generate watches
/// </summary>
public interface IWatchFactory
{
IWatch GetElegantWatch();
IWatch GetSportyWatch();
}
/// <summary>
/// Watch factory implementation of IWatchFactory interface
/// </summary>
public class WatchFactory : IWatchFactory
{
public IWatch GetElegantWatch()
{
return new ElegantWatch();
}
public IWatch GetSportyWatch()
{
return new SportyWatch();
}
}
Here is how to use it:
IWatchFactory watchFactory = new WatchFactory();
IWatch watch = watchFactory.GetElegantWatch();
System.Diagnostics.Debug.WriteLine(watch.GetType());
watch = watchFactory.GetSportyWatch();
System.Diagnostics.Debug.WriteLine(watch.GetType());
No comments:
Post a Comment