C# difference between singleton and factory pattern
Singleton pattern ensures only one instance of the type always be available for the client(s).Let us look into the below code
The constructor is defined as private ensuring that no instance of the class can be created. Singleton keeps common data in only one place and this can be done by using the "static" keyword where the property "Singleton" is defined.Next checking if the property value is null or not.If yes then we are creating an instance and if no then we are returning back the old instance only.This is done inside the CreateInstance method The client invocation part is as under
The factory pattern deals with how an object is created. It gets classified under the creational pattern.We can go for a factory pattern when we need for
a) Object creation without exposing it to client
b) Refer to newly created objects through interface.
Factory pattern defines an interface for creating an object, but let the classes that implement the interface decide which class to instantiate.
Singleton pattern ensures only one instance of the type always be available for the client(s).Let us look into the below code
class Singleton { private static Singleton singletonInstance; private Singleton(){} public static Singleton CreateInstance() { return singletonInstance == null ? new Singleton() : singletonInstance; } }
The constructor is defined as private ensuring that no instance of the class can be created. Singleton keeps common data in only one place and this can be done by using the "static" keyword where the property "Singleton" is defined.Next checking if the property value is null or not.If yes then we are creating an instance and if no then we are returning back the old instance only.This is done inside the CreateInstance method The client invocation part is as under
var _singletonInstance = Singleton.CreateInstance();
The factory pattern deals with how an object is created. It gets classified under the creational pattern.We can go for a factory pattern when we need for
a) Object creation without exposing it to client
b) Refer to newly created objects through interface.
Factory pattern defines an interface for creating an object, but let the classes that implement the interface decide which class to instantiate.
0 comments:
Post a Comment