How do you use factory template interfaces in a domain-driven design?

Does it make sense to use interfaces for your default domain object factories, or should interfaces be reserved for factory classes only when you need them?

public IUserFactory
{
    User CreateNewUser();
}

public UserFactory : IUserFactory
{
    public User CreateNewUser()
    {
        return new User();
    }
}
+3
source share
5 answers

Here's a translation of the same problem in Java.

Source example

public interface UserFactoryIF
{
   User createNewUser();
}

Then Factory implementation

public class UserFactory implements UserFactoryIF
{
     public User createNewUser()
     {
         // whatever special logic it takes to make a User
         // below is simplification
         return new User();
     }
}

factory, . , , factory . , :

public interface User
{
    public String getName();
    public long getId();
    public long getUUID();
    // more biz methods on the User
}

factory :

public class UserFactory {

    public static User createUserFrom(Person person) {
        // ...
        return new UserImpl( ... );
    }

    public static user createUserFrom(AmazonUser amazonUser) {
         // ... special logic for AmazonWS user
        return new UserImpl( ... );          
    }

    private static class UserImpl implements User {
       // encapsulated impl with validation semantics to
       // insure no one else in the production code can impl
       // this naively with side effects
    }
}

, .

+2

, Factory.

Factory " , , . Factory ." - Wikipedia

, - . , . Factory , .

. , , , , , .

+7

; -, - , .

+5

factory , IoC, , , , , .

Unit IoC ( ), , , .

, , Visual Studio, , " " , .

+2

Two things: (1) I will wait until I need (or see an impending need) an alternative implementation before I create the interface, and (2) the interfaces almost always simplify unit testing, especially with ridicule, so I often come up with the need for an interface.

+2
source

All Articles