damned
damned

Reputation: 71

You can create class object only using second class (first class doesn't have constructor?)

Example from ScriptHookDotNet:

First class:

public sealed class Vehicle : GTA.base.HandleObject
//Member of GTA

public abstract class HandleObject : GTA.base.Object
//Member of GTA.base

public abstract class Object
//Member of GTA.base

Second class:

public sealed class World
//Member of GTA

Method used:

public static GTA.Vehicle CreateVehicle(GTA.Vector3 Position)

You can't create object from Vehicle just using:

Vehicle veh = new Vehicle();

Because Vehicle doesn't have constructor.

But you can using this code:

Vehicle veh = World.CreateVehicle(params);

How it's made?

Upvotes: 2

Views: 1049

Answers (3)

Tejs
Tejs

Reputation: 41256

The constructor is private, so they force you to use the specific method to create an instance. This is known as a Factory pattern; internally to the World class, that method has the capacity to create a new instance of the Vehicle with the constructor, but you cannot.

EDIT: If you want to create this kind of functionality, then you would do something like this:

public class MyPublicClass
{
    public MyPrivateClass CreateClass()
    {
         return MyPrivateClass.GetInstance();
    }
}

public class MyPrivateClass
{
    internal static MyPrivateClass GetInstance() { return new MyPrivateClass(); }        

    protected MyPrivateClass() { }
}

Upvotes: 8

Steven Magana-Zook
Steven Magana-Zook

Reputation: 2759

The constructor of the Vehicle class is anything but public (protected, internal, private) by design, because the class creators wanted to have finer control over how the objects were created.

In addition to the Factory pattern already mentioned, the singleton pattern also uses this method of class creation to ensure that only one instance of a particular class is created (http://www.yoda.arachsys.com/csharp/singleton.html).

I have also seen this pattern used by the Event Aggregator(http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.20).aspx) class that needs knowledge about the events you want to publish or subscribe to, which seems to be the case here. For example, if you simply instantiated a Vehicle class, how would the World class know to put that vehicle into the scene or to use that vehicle object when interacting with other objects? Instead of designing some method to add the vehicle to the world (i.e. worldInstance.AddVehicle(..) I think in this case World was designed to control how objects interacting with the World are created.

For more information on the Factory pattern see: http://msdn.microsoft.com/en-us/library/ee817667.aspx

Upvotes: 0

umlcat
umlcat

Reputation: 4143

Additional comment: If you can modify the code, you may want to add a custom public constructor to your classes.

Think different ;-)

Upvotes: 0

Related Questions