Factory pattern in C#: How to ensure an object instance can only be created by a factory class?

后端 未结 17 1751
小鲜肉
小鲜肉 2020-11-29 16:51

Recently I\'ve been thinking about securing some of my code. I\'m curious how one could make sure an object can never be created directly, but only via some method of a fact

17条回答
  •  感动是毒
    2020-11-29 17:20

    I'd put the factory in the same assembly as the domain class, and mark the domain class's constructor internal. This way any class in your domain may be able to create an instance, but you trust yourself not to, right? Anyone writing code outside of the domain layer will have to use your factory.

    public class Person
    {
      internal Person()
      {
      }
    }
    
    public class PersonFactory
    {
      public Person Create()
      {
        return new Person();
      }  
    }
    

    However, I must question your approach :-)

    I think that if you want your Person class to be valid upon creation you must put the code in the constructor.

    public class Person
    {
      public Person(string firstName, string lastName)
      {
        FirstName = firstName;
        LastName = lastName;
        Validate();
      }
    }
    

提交回复
热议问题