What if I don't need a special factory class and I want a concrete client to instantiate right parts. The client needs to call Hello() from that part. Everywhere else the focus is on making the factory method a method of a special creator class. But here it is right away in a client. Is this still a factory method pattern and is it even correct to use it as shown below?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
AClient c1 = new ClientUsingPart1();
c1.Foo();
AClient c2 = new ClientUsingPart2();
c2.Foo();
Console.ReadKey();
}
}
abstract class AClient
{
public AClient() { this.ipart = Create(); }
public void Foo() { ipart.Hello(); }
// many other methods
// ...
public abstract IPart Create(); // factory method
IPart ipart;
}
class ClientUsingPart1 : AClient
{
public override IPart Create() { return new Part1(); }
}
class ClientUsingPart2 : AClient
{
public override IPart Create() { return new Part2(); }
}
interface IPart
{
void Hello();
}
class Part1 : IPart
{
public void Hello() { Console.WriteLine("hello from part1"); }
}
class Part2 : IPart
{
public void Hello() { Console.WriteLine("hello from part2"); }
}
}