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();
>> }
>> }