Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Created March 28, 2016 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yemrekeskin/f659cc9e561883f902f1 to your computer and use it in GitHub Desktop.
Save yemrekeskin/f659cc9e561883f902f1 to your computer and use it in GitHub Desktop.
namespace FactoryMethod.Sample2
{
class Program
{
static void Main(string[] args)
{
// normal kullanım
PDFReader pdfreader = new PDFReader();
pdfreader.Read();
pdfreader.Extract();
// 1. kullanım
DocumentReaderFactory readerFac = new DocumentReaderFactory();
IDocumentReader pdfReader = (PDFReader)readerFac.Get("PDF");
pdfReader.Read();
pdfReader.Extract();
// 1.1 generic version
IDocumentReader pdfReader1 = (PDFReader)DocumentFactory.Get();
IDocumentReader wordReader1 = (MsWordReader)DocumentFactory.Get();
Console.ReadLine();
}
}
public interface IDocumentReader
{
void Read();
void Extract();
}
public class PDFReader
: IDocumentReader
{
public void Read()
{
throw new NotImplementedException();
}
public void Extract()
{
throw new NotImplementedException();
}
}
public class MsWordReader
: IDocumentReader
{
public void Read()
{
throw new NotImplementedException();
}
public void Extract()
{
throw new NotImplementedException();
}
}
// 1
public class DocumentReaderFactory
{
// burada string tipi enum da kullanabiliriz.
public IDocumentReader Get(string readerType)
{
switch (readerType)
{
case "PDF":
return new PDFReader();
case "MsWord":
return new MsWordReader();
default:
return new PDFReader();
// örneğin burası için NULL object deseni kullanılarak nul tanımlı bir sınıf yazılabilir.
// veya exception fırlatılır throw new Exception("Invalid DocumentReader type");
}
}
}
// 1.1 generic version
class DocumentFactory
where T : IDocumentReader, new()
{
private static IDocumentReader opr = null;
public static IDocumentReader Get()
{
return opr = new T();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment