Run Code
|
Code Wall
|
Users
|
Misc
|
Feedback
|
About
|
Login
|
Theme
|
Privacy
The abstract factory design pattern implemented in c# using generics.
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { // Get the list of factories var factories = GetFactories(); // Iterate through the list of factories, creating the instance and running a method. foreach(var f in factories) { var x = f.CreateInstance(); x.DoSomething(); } } // Creates a list of IFactory with different implementations static List<IFactory> GetFactories() { return new List<IFactory>() { new Concrete.Factory<Concrete.A>(), new Concrete.Factory<Concrete.B>() }; } } // This is the abstract factory. public interface IFactory { IBase CreateInstance(); } // This is the interface the abstract factory returns. public interface IBase { void DoSomething(); } } namespace Concrete { // This is a concrete implementation of the abstract factory using generics. // I've put it in a different namespace to make the decoupling between this and the using class very clear. public class Factory<T> : Rextester.IFactory where T : Rextester.IBase, new() { public Rextester.IBase CreateInstance() { return new T(); } } // This is a concrete implementation of the IBase interface public class A : Rextester.IBase { public void DoSomething() { Console.WriteLine("This is A"); } } // This is a different concrete implementation if the IBase interface public class B : Rextester.IBase { public void DoSomething() { Console.WriteLine("This is B"); } } }
Show compiler warnings
[
+
]
Show input
Compilation time: 0,16 sec, absolute running time: 0,08 sec, cpu time: 0,08 sec, average memory usage: 13 Mb, average nr of threads: 3
edit mode
|
history
|
discussion
This is A This is B