vendredi 30 septembre 2016

Composite design pattern in Python with IoC

It is said that Python does not need an IoC container. However, all answers there pay attention on replacing one implementation with another and ignore the fact that this is not the only purpose of the DI.

How to create a composite that automatically receives all its leaves in runtime in a pythonic way?

If I were not clear enough, take a look at this Java & Spring example:

interface PermissionEvaluator {
    boolean isAllowed(User who, Action what);
}    

interface PermissionVoter extends PermissionEvaluator {}

@Service
@Primary
class CompositePermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private List<PermissionVoter> voters;

    public boolean isAllowed(User who, Action what) {
        for (PermissionVoter voter : voters) {
            if (voter.isAllowed(who, what)) {
                return true;
            }
        }
        return false;
    }
}

@Component
@Order(2)
class PermissionVoter1 implements PermissionVoter { /* ... */ }

@Component
@Order(3)
class PermissionVoter2 implements PermissionVoter { /* ... */ }

@Component
@Order(1)
class PermissionVoter3 implements PermissionVoter { /* ... */ }

Aucun commentaire:

Enregistrer un commentaire