(the Productes) by letting a class (the Creator) deciding which class to instantiate depending on a specific reason.
For example, in case that the creation process depends on user input .
In the world of GIS, there is a map which includes many various layers.
The client chooses what kind of Layers to be added to a given map .
//The codeFile:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace factoryMethodPattern
{
//the Constructor
public class Map
{
List<Layer> _layers;//internal list of Layers
public Map()
{
_layers = new List<Layer>();
}
public int numberOfLayers()
{
return _layers.Count;
}
//the Factory Method
public Layer addLayer(LayerType type)
{
Layer lr;
//deciding which class to instantiate
if(type== LayerType.points)
{
lr= new PointLayer(this);
}
else
if(type==LayerType.lines)
{
lr= new LineLayer(this);
}
else
throw new ApplicationException("Error!");
//adding the constructed layer to the internal list, then returning it
_layers.Add(lr);
return lr;
}
}
//Products
public abstract class Layer
{
protected Map _map;
public Layer(Map parentMap)
{ _map = parentMap; }
public abstract void draw();
}
//internal classes to force the client uses the Constructor class
//we may add "public" to provide direct access (in addition to using the Constructor)
class PointLayer : Layer
{
public PointLayer(Map parentMap):base(parentMap)
{ }
public override void draw()
{
// drawing on the map
Console.WriteLine("drawing Point Layer..");
}
}
class LineLayer : Layer
{
public LineLayer(Map parentMap): base(parentMap)
{ }
public override void draw()
{
// drawing on the map
Console.WriteLine("drawing Line Layer..");
}
}
public enum LayerType
{
points,lines
}
}
// The Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace factoryMethodPattern
{
class Program
{
static void Main(string[] args)
{
Map m = new Map();
Layer l;
l= m.addLayer(LayerType.points);
l.draw();
l = m.addLayer(LayerType.lines);
l.draw();
Console.WriteLine("the Map contains {0} Layers.",m.numberOfLayers());
Console.ReadLine();
}
}
}
No comments:
Post a Comment