How can I prevent instances of objects except for a specific factory class?

In short, I want to prevent the creation of instances of objects anywhere except for the assigned static methods in the factory class.

Is it possible?

+3
source share
3 answers

If your factory and your classes are in the same assembly, you can tag the internal constructors. This will ensure that no classes outside the assembly can call constructors (without reflection). Your factory, located in the same assembly, sees the constructors as public and, therefore, can access them.

factory . , , , , factory.

+9

, Reflection :

    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
+1

?

"use factory!" . ( , " , factory:-)

factory .

0

Source: https://habr.com/ru/post/1723812/


All Articles