Creating new instance of object without using "new" - c#

I faced with the code below
XmlReader xmlreader =
XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
here to make a new object of XmlReader, it just used calling method of XmlReader.
I know here Create is a static method, but it is a little odd for me.
I used to exploit new word to command making new instance.
Can anyone please tell me how does this line works?

The method you're calling does it for you:
public class XmlReader {
public static XmlReader Create(String url) {
// There's probably a lot of fancy code in this method, but it'll use new somewhere
return new XmlReader(...);
}
}
(It's possible to avoid new altogether by using a technique called reflection, but that's not what's going on here.)

This is an example of a factory method. (Which can often be a step toward using a separate factory object.)
Somewhere in XmlReader.Create it is internally making use of the new keyword. In order to instantiate a new instance of an object, you need to use new to call a constructor. To reduce coupling between objects, however, you may abstract that behind a factory method or factory object.
For example, these two implementations do roughly the same thing:
public class Widget
{
public Widget() { }
}
//... elsewhere ...
var widget = new Widget();
And:
public class Widget
{
private Widget() { }
public static Widget Create()
{
return new Widget();
}
}
//... elsewhere ...
var widget = Widget.Create();
In an example this simple, there's little difference between the two. As code evolves and becomes more complex, there can be a number of compelling reasons to choose one over the other. For example:
There are complex constructors and you want to expose a simple interface for building an instance.
The constructors are likely to change often and you want consumers of your library to have a single unchanging interface.
There is significant logic invoked when building an object and you want to move that logic to its own object.
You want to use a separate object for mockability in automated testing.
You have a more complex inheritance structure and want to expose a top-level abstract factory.
etc.

It's a static method that, in it's body, creates a new object (using new) and returns it.
You can emulate the pattern like so:
public class Foo
{
public static Foo Create()
{
return new Foo();
}
}

public class Foo
{
public string Prop { get;set; }
public Foo(string prop)
{
Prop = prop;
}
public static Foo Create(string prop)
{
return new Foo(prop);
}
}
This is how it can look like under.

There are several reasons to create factory Methods. Do you want control about all the Instances created of a Type? For example you could do something like that:
public class MyClass {
private MyClass() // private constructor optional
{}
public void Create()
{
return new MyClass();
}
}
(private constructors are often used to implement the Singleton Pattern)
Factory Methods could also be in a seperate Class.
public class MyClass {
internal MyClass() // means only Classes of same assembly may access this
{}
}
public class MyClassFactory {
public void NewMyClass()
{
// Do some license checking here or whatever
return new MyClass();
}
}
Factory Methods define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Read more about Factory Methods here.

Related

Factory pattern: Restrict object construction to factory

I have a class T and a factory TFactory that creates objects of type T.
I want to make sure that only the factory is allowed to create new T objects.
A halfhearted solution would be to require the factory as a parameter in T's constructor, for the only purpose that only somebody who at least brings a factory object can create T's:
class T
{
public T(TFactory Tf)
{
if (!(Tf is TFactory))
throw new InvalidOperationException("No factory provided");
}
}
But wherever a TFactory is at hand, one could construct T's.
Another approach would be to check via stack tracing, if the constructor call really came from within a TFactory, but this seems overkill to me.
A third apporach would be to put both T and TFactory in an assembly of their own, ad make T's constructor internal. But a new project and assembly just for this purpose?
Any better idea anybody?
(Although my code is C#, this is probably a more general question)
Here's something very similar to your third approach: declare the factory as a inner class of T, and make T's constructor private:
public class T {
public class Factory {
public T GetT() {
return new T(); // simple implementation just for an example here
}
}
private T() {}
}
Since Factory is inside T, it can access the private constructor, but outside code cannot. If you don't want to create a separate assembly, you could consider this approach.
Note that you could still put the factory class and T in two different files, with partial classes:
public partial class T {
private T() {}
// other stuff about T here...
}
// in another file
public partial class T {
public class Factory {
public T GetT() {
return new T();
}
// other stuff about Factory here...
}
}
public abstract class T { }
public class TFactory
{
public T CreateT() => new TImpl();
private class TImpl : T { }
}
The second approach is the worst one. That behavior is absolutely unobvious and unclear to a client. Stack tracing also slows down execution. The 1st and the 2nd make sense.
If you want to have total control of instance creation put it into the type. Use a factory method. Remember, one should be reasonable when putting constraint on instance creation. E.g. the instance should be initiated with a polymorphal (virtual) method. One can't call such a method from a constructor (a very bad practice), so the method should be called after construction. For not to put that responsibility on the client, hide the constructor from one and provide a factory method.
abstract class Base
{
protected abstract void Initialize();
}
class Derived : Base
{
protected Derived() { /* ... */}
protected override void Initialize() { /* ... */}
public Derived CreateDerived()
{
var derived = new Derived();
derived.Initialize();
return derived;
}
}

Listen to object instantiation

I have interface and some classes that implement this interface.
I want to listen for any object that will be instantiated and check if this object implements my interface.
My primary reason is to store all references to this kind of objects and simply call a method of interface to all objects.
As Kyle said in the comments the constructor of an abstract class would be the best choice. Or a factory that must be used for construction of those kind of objects.
But if this is not an option maybe the following approach is acceptable in your case.
If the "listener" is globally accessible (e.g. something static) you can add methods like Register(IYourInterface obj) and Unregister(IYourInterface obj) to it and ensure that every class that implements the interface will call these methods on construction / deconstruction. Not the cleanest way, but it will work as long as you maintain this behavior.
Example:
public static class Listener
{
private static List<IMyInterface> objects = new List<IMyInterface>();
public static void Register(IMyInterface obj)
{
if (!objects.Contains(obj))
objects.Add(obj);
}
public static void Unregister(IMyInterface obj)
{
if (objects.Contains(obj)
objects.Remove(obj);
}
public static void DoSomethingWithObjects()
{
foreach (IMyInterface obj in objects)
// do something ...
}
}
public class SomeTestClass : IMyInterface
{
public SomeTestClass()
{
Listener.Register(this);
}
}
There are a few ways to go about this.
Use a base abstract class
Easiest solution is to have a base class that everything inherits from. This kind of defeats the purpose of the interface, but this is the only way you can add this sort of code for creation. You could do something like:
public abstract class AbstractBaseClass
{
public AbstractBaseClass()
{
ObjectRegister.StoreReference(this);
}
public abstract void MethodToCall();
}
public class SubClass : AbstractBaseClass
{
public SubClass() : base() //Don't forget 'base()'!
{
//Your code here
}
public override void MethodToCall()
{
Console.WriteLine("Called in SubClass");
}
}
The abstract MethodToCall could also be virtual if you want to provide a default action, but if it's abstract the compiler will complain that you haven't implemented it in a similar way to interfaces.
Use a public static instantiating method
A bit more verbose, but can be seen in things like Unity. In this case, instead of doing x = new Y(), you have a public static method, perhaps a generic one, that creates the class for you, registers it, then returns that instance. Assuming your interface is called 'IRegisterable', you could have something like:
public static class ObjectRegister
{
//Note the 'where', which constrains T to be something that
//implements IRegisterable
public static T Instantiate<T>() where T:IRegisterable
{
T obj = new T();
StoreReference(obj);
return obj;
}
private static StoreReference(IRegisterable obj)
{
//Do your storing code here. This doesn't even need to be a method
//if your reference storing stuff only happens on object creation
}
}
//Elsewhere, where class 'Thing' implements IRegisterable
Thing x = ObjectRegister.Instantiate<Thing>();
//x is now registered. No need to do x = new Thing()
string y = ObjectRegister.Instantiate<string>();
//Error: string does not implement IRegisterable
Unfortunately, supplying constructor arguments this way isn't easy. You could just have an Init() method though which acts as a sort of fake constructor.

Abstract singleton inheritance with multiple sub-classes

Continuing with the answer given here, is there a way to allow MyChildSingleton to be abstract, and then let it's sub-classes define their own constructors? An example of what I would like to do:
public abstract class SingletonBase<T>
where T : SingletonBase<T>, new()
{
private static T _instance = new Lazy<T>(() => new T());
public static T Instance
{
get
{
return _instance;
}
}
}
public abstract class DefaultConfigData: SingletonBase<DefaultConfigData>
{
// This class won't compile since it's abstract, and SingletonBase<T>
// has a new() restriction on T
// Also, this class is immutable and doesn't change state
public virtual string SomeData { get; } = "My Default Data String";
public virtual double MoreData { get; } = 2.71;
public virtual double SomeFunction(double num)
{ return num + 2*MoreData; }
public DefaultConfigData() { ; /* nothing to do here */ }
// Another 50 or so default values/functions...
// enough to be tedious to redefine in multiple places,
// and adding a constructor that takes every value would be ridiculous.
// It would be possible to encapsulate this data, but I'm not
// yet sure how this should be done, so I haven't gone there yet
}
public class SpecificConfigData1: DefaultConfigData
{
public override string SomeData { get; } = "A Different String";
public SpecificConfigData1() { ; /* nothing to do here */ }
}
public class SpecificConfigData2: DefaultConfigData
{
public override double MoreData { get; } = 3.14;
public SpecificConfigData2() { ; /* nothing to do here */ }
}
// Downstream developers may need to define additional ConfigData classes
public class Library
{
public static double doSomething(DefaultConfigData data) { return data.MoreData + 2.0; }
}
public class Program
{
private readonly DefaultConfigData data;
public Program(bool choice)
{
data = (choice) ? SpecificConfigData1.Instance : SpecificConfigData2.Instance;
}
public static void Main()
{
Program prog = new Program(/*run-time user input here*/);
Console.PrintLine(Library.doSomething(prog.data));
}
}
Using a singleton pattern seemed like a good idea, because for each specific subclass the data only needs to exist in one place, and since it's immutable this avoids most of the issues associated with singletons (global mutable state, etc.). Providing the singleton functionality in an abstract base class would avoid the boilerplate of putting the private instance and public get property, which is what I'm doing now in each sub-class. This really isn't too onerous a requirement, I'm sure I could live with it.
I don't want to make DefaultConfigData and it's data static, because then I can't inherit from it and have my library functions know how to interact with it (no support for metaclasses in C#). Also, I don't want to use an interface, because so much of the functionality is shared, and I couldn't define that in the interface.
I would also welcome comments on alternative approaches, if the one I'm trying to do can't be accomplished, or if another way is simply easier. I know that a factory pattern could also work here, and that's something I intend to try eventually.
Last, why is this even an issue? Why wasn't the decision made to let abstract classes satisfy the new() requirement, provided that any of their sub-classes also satisfy a new()?
Note that my "users" are other internal developers/my future self. Source code is usually the deliverable, and pushing checks to run time are ok in this environment.
The easiest solution I can think of is using a factory pattern. The other solution is you need to keep DefaultConfigData class generic, like:
public abstract class DefaultConfigData<T>: SingletonBase<T>
where T : DefaultConfigData<T>, new()
{ }
The problem with that is when you want to use DefaultConfigData anywhere, you have to make that method or class generic, like the doSomething method:
public static double doSomething<T>(DefaultConfigData<T> data)
where T : DefaultConfigData<T>, new()
{
return data.MoreData + 2.0;
}
And as you can guess, that can get really annoying. So, back to the factory pattern:
public static class MyFactory<T>
{
private static Lazy<T> _instance = new Lazy<T>(CreateUsingReflection);
public static T Instance
{
get
{
return _instance.Value;
}
}
private static T CreateUsingReflection()
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
ConstructorInfo ctor = typeof(T).GetConstructor(flags, null, Type.EmptyTypes, null);
return (T)ctor.Invoke(null);
}
}
And, you can use it like so:
SpecificConfigData1 scd1 = MyFactory<SpecificConfigData1>.Instance;
Note that none of your classes need to inherit from MyFactory. You are free to create classes that inherit from anything (or nothing), as long as you have a parameterless constructor. You could restrict the T in MyFactory<T> using where T : new(), in which case you will get compile-time guarantee that the class supports a parameterless public constructor, and can avoid reflection by creating the class using just new T(). Without the new() restriction, it can create singletons using a private constructor, but you lose the compile-time checking that a parameterless constructor exists.
Actually, there is another solution. It is much more complex, but it is quite powerful if you use it to its fullest: an IoC container such as Autofac, Unity, and many others. These can help manage your instances, so that you can specify the Types that should be singletons. I won't go over how to use one since that is a whole different topic, and would require multiple paragraphs just to explain the basics.

Factory Pattern to build many derived classes

I have a factory object ChallengeManager to generate instances of a Challenge object for a game I'm building. There are many challenges. The constructors for each Challenge class derivation are different, however there is a common interface among them, defined in the base class.
When I call manager.CreateChallenge(), it returns an instance of Challenge, which is one of the derived types.
Ideally, I would like to keep the code for the object construction inside the derived class itself, so all the code related to that object is co-located. Example:
class Challenge {}
class ChallengeA : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeA();
}
}
class ChallengeB : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeB();
}
}
Now, my ChallengeManager.CreateChallenge() call only needs to decide the class to call MakeChallenge() on. The implementation of the construction is contained by the class itself.
Using this paradigm, every derived class must define a static MakeChallenge() method. However, since the method is a static one, I am not able to make use of an Interface here, requiring it.
It's not a big deal, since I can easily remember to add the correct method signature to each derived class. However, I am wondering if there is a more elegant design I should consider.
I really like the pattern you are describing and use it often. The way I like to do it is:
abstract class Challenge
{
private Challenge() {}
private class ChallengeA : Challenge
{
public ChallengeA() { ... }
}
private class ChallengeB : Challenge
{
public ChallengeB() { ... }
}
public static Challenge MakeA()
{
return new ChallengeA();
}
public static Challenge MakeB()
{
return new ChallengeB();
}
}
This pattern has many nice properties. No one can make a new Challenge because it is abstract. No one can make a derived class because Challenge's default ctor is private. No one can get at ChallengeA or ChallengeB because they are private. You define the interface to Challenge and that is the only interface that the client needs to understand.
When the client wants an A, they ask Challenge for one, and they get it. They don't need to worry about the fact that behind the scenes, A is implemented by ChallengeA. They just get a Challenge that they can use.
You're "decentralizing" the factory, such that each subclass is responsible for creating itself.
More commonly you would have a central factory that would know about the possible subtypes and how to construct them (often enough, simply by creating a new instance and returning that instance typed as a common interface or common base class). That approach avoids the issue you currently have. I also see no benefit to your current approach. You are currently gaining no encapsulation or code reuse over the more typical implementation of a factory.
For additional reference, have a look at
http://www.oodesign.com/factory-pattern.html
Not necessarily the answer you are looking for but...
You can use following implementation, if you can move away from static method per class.
using System;
public class Test
{
public static void Main()
{
var c1 = ChallengeManager.CreateChallenge();
var c2 = ChallengeManager.CreateChallenge();
//var c = ChallengeManager.CreateChallenge<Challenage>(); // This statement won't compile
}
}
public class ChallengeManager
{
public static Challenage CreateChallenge()
{
// identify which challenge to instantiate. e.g. Challenage1
var c = CreateChallenge<Challenage1>();
return c;
}
private static Challenage CreateChallenge<T>() where T: Challenage, new()
{
return new T();
}
}
public abstract class Challenage{}
public class Challenage1: Challenage{}
public class Challenage2: Challenage{}

Why do we need a private constructor?

If a class has a private constructor then it can't be instantiated.
So, if I don't want my class to be instantiated and still use it, then I can make it static.
What is the use of a private constructor?
Also, it's used in the singleton class, but except for that, is there any other use?
(Note: The reason I am excluding the singleton case above is that I don't understand why we need a singleton at all when there is a static class available. You may not answer this for my confusion in the question. )
Factory
Private constructors can be useful when using a factory pattern (in other words, a static function that's used to obtain an instance of the class rather than explicit instantiation).
public class MyClass
{
private static Dictionary<object, MyClass> cache =
new Dictionary<object, MyClass>();
private MyClass() { }
public static MyClass GetInstance(object data)
{
MyClass output;
if(!cache.TryGetValue(data, out output))
cache.Add(data, output = new MyClass());
return output;
}
}
Pseudo-Sealed with Nested Children
Any nested classes that inherit from the outer class can access the private constructor.
For instance, you can use this to create an abstract class that you can inherit from, but no one else (an internal constructor would also work here to restrict inheritance to a single assembly, but the private constructor forces all implementations to be nested classes.)
public abstract class BaseClass
{
private BaseClass() { }
public class SubClass1 : BaseClass
{
public SubClass1() : base() { }
}
public class SubClass2 : BaseClass
{
public SubClass2() : base() { }
}
}
Base Constructor
They can also be used to create "base" constructors that are called from different, more accessible constructors.
public class MyClass
{
private MyClass(object data1, string data2) { }
public MyClass(object data1) : this(data1, null) { }
public MyClass(string data2) : this(null, data2) { }
public MyClass() : this(null, null) { }
}
As Stefan, Adam and other have pointed out, private constructors are useful in cases where it is undesirable for a class to be created by code outside of the class. Singletons, factories, static method objects are examples of where being able to restrict constructon of a type is useful to enforce a particular pattern.
To respond to the second part of your question about why singletons are needed if static classes exist: singletons and static classes are not equivalent.
For example, a singleton class can implement an interface, a static class cannot. A singleton object may be passed to methods as a parameter - this is not so easy to do with static classes without resorting to wrapper objects or reflection. There are also cases where you may want to create an inheritance hierarchy in which one (or more) of the leaf classes are singleton - this is not possible with static classes either. As another example, you may have several different singletons and you may want to instantiate one of them at runtime based on environmental or configurational parameters - this is also not possible with static classes.
It is important to understand the language features and choose the right one for the job - they're there for a reason.
Sometimes you shouldn't be able to instantiate a class. This makes this explicit and enforces this at the compiler level.
Singletons are just one use case. Constants classes, static methods classes, and other types of patterns dictate that a class should not be instantiable.
Purpose to create the private constructor within a class
To restrict a class being inherited.
Restrict a class being instantiate or creating multiple instance/object.
To achieve the singleton design pattern.
public class TestPrivateConstructor
{
private TestPrivateConstructor()
{ }
public static int sum(int a , int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
// calling the private constructor using class name directly
int result = TestPrivateConstructor.sum(10, 15);
// TestPrivateConstructor objClass = new TestPrivateConstructor(); // Will throw the error. We cann't create object of this class
}
}
You can use it to force a singleton instance or create a factory class.
A static method can call the private constructor to create a new instance of that class.
For example a singleton instance:
public class Foo
{
private Foo (){}
private Foo FooInstance {get;set;}
public static Foo GetFooInstance ()
{
if(FooInstance == null){
FooInstance = new Foo();
}
return FooInstance;
}
}
This allows only one instance of the class to be created.
Well if your only objective is that you don't want it to be instantiated, then making it static is sufficient.
If, otoh, you simply don't want it to be instaniated frm outside the class, (maybe you only want users to get one by using a static factory on the class) - then you need a private ctor to allow those publicly accessible static factories to instantiate it.
Historically, remember that making a class static has not always been around... Making the ctor private was a way to make it not-instantiatable (is this a word? ) before the static keyword could be applied to a class...
Regarding singletons - singleton is a design pattern used when the environment and requirements satisfy similar motivations for the pattern's use; static classes are a language feature.
As LBushkin's answer discusses, while some of the goals of using singleton can be met using static classes, a particular implementation of singleton may exceed the feature set of static classes alone.
If the class ONLY has private constructors, it cannot be instantiated from outside.
You can also have private constructors and public constructors with different signatures.
If you want to create a factory for a class, you can use a private constructur, and add some static "factory" methods to the class itself to create the class.
An example for this is the Graphics class, with the From* methods.
Private constructors is a special instance constructor. and are used in some cases where we create a class which only have static members, so creating instance of this class is useless, and that is where private constructor comes into play.
If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
example:
class LogClass {
public static double e = Math.E; //2.71828
// Private Constructor:
private LogClass() {
}
}
The declaration of the empty constructor prevents the automatic generation of a parameter less constructor.
If you do not use an access modifier with the constructor it will still be private by default.
Read more: https://qawithexperts.com/tutorial/c-sharp/32/private-constructor-in-c-sharp

Categories