1

Let's say I have an Apple Class and an AppleFactoryClass. Nobody should be able to use Apple redApple = new Apple(). Instead new Apples should only be able to be created from AppleFactory.Create().

This mean the Constructor of Apple must be inaccessible for everyone but the AppleFactory Class.

How can this be done?

EDIT: Apple is more like an AppleModel. So there is only Properties in there.

Thypari
  • 801
  • 1
  • 6
  • 22
  • 2
    You're looking for something similar to the friend relationship from C++, which is not available in C#. If I may offer an opinion, you shouldn't be worrying about this. If somebody in future wants to create an instance of Apple themselves then that it their issue, not yours – LordWilmore Dec 06 '17 at 15:41

3 Answers3

2

If you want a different type to act as the factory, then the closest you can get is internal:

public sealed class Apple() {
    internal Apple() {} 
}
public class AppleFactory() {
    public Apple CreateApple() => new Apple();
}

However, if you can have the factory as a static method on Apple, then you can keep everything private:

public sealed class Apple() {
    private Apple() {} 
    public static Apple Create() => new Apple();
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Problem is the Apple is more like an AppleModel. So there's only Properties in there, no real Logic. I'd rather not put the Factory inside Apple itself. – Thypari Dec 06 '17 at 15:45
  • @Thypari I hear you; I'm just telling you what the options are :) Note - if this `Apple` is from code-gen tools: `partial class` may help - allows you to add functionality to a class in a separate file. Similarly: extension methods. – Marc Gravell Dec 06 '17 at 15:49
1

You can let the Apple class be its own factory.

public class Apple
{
    private Apple()
    {}

    internal static Apple Create()
    {
        var apple = new Apple();
        // TODO: Initialize
        return apple;
    }
}

The real Apple factory can then call this factory method:

public class AppleFactory() {
    public CreateApple() => Apple.Create();
}

By making Apple.Create() internal, you can restrict its usage to the current assembly. The constructor can be called only insde Apple anway, because it is private.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Problem is the Apple is more like an AppleModel. So there's only Properties in there, no real Logic. – Thypari Dec 06 '17 at 15:43
0

You can make Apple abstract, then make a private subclass inside AppleFactory.

However, you can't prevent other people from making their own subclasses.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964