Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Create Instance Of Class Through Method Call Only?
Message
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Divers
Thread ID:
01464302
Message ID:
01464317
Vues:
50
Look at my code again. You haven't included the private CTOR in the Customer class...
To instantiate it you'd use Customer = Customer.GetInstance();
>Ok, This compiles and runs , but there's still a problem. Here's what I have:
>
>
>public class Customer
>{
>    public string Name { get; set; }
>
>    public static Customer GetInstance()
>    {
>        return new Customer();
>    }
>}
>
>
>
>
>public class Factory
>{
>    public Customer NewCustomer()
>    {
>        return new Customer();
>    }
>}
>
>
>
>static void Main(string[] args)
>{
>    // This works
>    Factory f = new Factory();
>    Customer customer = f.NewCustomer();
>
>    // This does too. I want to stop this type of instantiation
>    Customer cust = new Customer();
>
>}
>
>
>Notice that I can still directly instantiate a customer. if I add a private, parameterless CTOR to Customer, I get an exception.
>
>
>>>Is it possible to prevent a class from being instantiated from outside a class? Sort of like a factory pattern. I would like to change my
>>>project so that new instances can only come through a method call.
>>>
>>>How do I do this?
>>
>>Something like:
   public class SomeClass
>>    {
>>        private SomeClass()
>>        {
>>        }
>>
>>        public static SomeClass GetInstance()
>>        {
>>            return new SomeClass();
>>        }
>>    }
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform