开发者

How can I prevents objects being instantiated except in a defined 'factory class'?

In short I want to prevent objects being instantiated anywhere except开发者_StackOverflow in designated static methods in a object factory class.

Is this possible?


If your factory and your classes are in the same assembly you can mark the constructors internal. This will make it so that no classes outside the assembly can call the constructors (without reflection). Your factory, being in the same assembly, sees the constructors as public and, thus, can access them.

Alternatively, you can make the constructors private and use reflection inside your factory to instantiate the objects. You take a small hit using reflection but this doesn't have the assembly restriction and also serves to keep other classes in the same assembly from using anything other than the factory.


Some sample code I've put together with Reflection for instantiating an object with a private constructor:

    Private Shared Function CreateObject(Of t)() As t

    Try
        Dim ci As ConstructorInfo = GetType(Class1).GetConstructor(CType(BindingFlags.Instance + BindingFlags.NonPublic, _
                      BindingFlags), Nothing, Type.EmptyTypes, Nothing)

        Dim x As t = CType(ci.Invoke(Nothing), t)

        Return x

    Catch ex As NullReferenceException
        Throw New MissingMethodException("No private constructor found")

    Catch ex As Exception
        Throw
    End Try

End Function


How much protection do you need?

Just mark the constructor obsolete with a message saying "use factory!" should work in most cases. (if it doesn't work, add "you'll be fired if you don't use the factory :-) 

In the factory you turn the warning off.   

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜