I\'m looking for a simple example of how to implement a factory class, but without the use of a Switch or an If-Then statement. All the examples I can find use one. F
Why overcomplicate things? Here is one simple solution:
using System;
using System.Collections.Generic;
class Program
{
interface IPosition
{
string Title { get; }
}
class Manager : IPosition
{
public string Title
{
get { return "Manager"; }
}
}
class Clerk : IPosition
{
public string Title
{
get { return "Clerk"; }
}
}
class Programmer : IPosition
{
public string Title
{
get { return "Programmer"; }
}
}
class Factory
{
private List positions = new List();
public Factory()
{
positions.Add(new Manager());
positions.Add(new Clerk());
positions.Add(new Programmer());
positions.Add(new Programmer());
}
public IPosition GetPositions(int id)
{
return positions[id];
}
}
static void Main(string[] args)
{
Factory factory = new Factory();
for (int i = 0; i <= 2; i++)
{
var position = factory.GetPositions(i);
Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
}
Console.ReadLine();
}
}
Here is how to do this without using factory class at all:
using System;
using System.Collections.Generic;
class Program
{
interface IPosition
{
string Title { get; }
}
class Manager : IPosition
{
public string Title
{
get { return "Manager"; }
}
}
class Clerk : IPosition
{
public string Title
{
get { return "Clerk"; }
}
}
class Programmer : IPosition
{
public string Title
{
get { return "Programmer"; }
}
}
static void Main(string[] args)
{
List positions = new List { new Manager(), new Clerk(), new Programmer(), new Programmer() };
for (int i = 0; i <= 2; i++)
{
var position = positions[i];
Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
}
Console.ReadLine();
}
}