mercredi 27 janvier 2021

Express mutual connection at initialization

In cases where there is an object handling multiple other objects, how can the ownership be expressed at initialization?

For examples sake, let's say there is a Chicken hatching multiple eggs. It would not be good for the chicks to be without a parent, but the Chicken should also only focus its attention to its chicks. If this kind of relationship should be expressed at initialization, how would it be possible?

Which design pattern would be the best to use in this scenario?

It would be preferable to avoid using null if possible, because that might introduce ambiguity into the system. If it's unavoidable to use it, how can the ambiguity best be minimzed?

Example program:

public class MyClass {

    /**
     * Handles eggs
     * */
    public static class Chicken{
        private Egg[] eggs;
        
        public Chicken(Egg... eggs_){
            eggs = eggs_;
        }
        
        public void accept_signal(String message){
            /* ... */
        }
    }
    
    /**
     * Signals when its ready to hatch
     * */
    public static abstract class Egg{
        private final Chicken parent;
        public Egg(Chicken parent_){
            parent = parent_;
        }
        
        public void hatch(){
            parent.accept_signal("chirp chirp");
        }
    }
    
    /**
     * The resulting children to be handled
     * */
    public static class YellowChick extends Egg{
        public YellowChick(Chicken parent_){
            super(parent_);
        }
    }
    
    public static class BrownChick extends Egg{
        public BrownChick(Chicken parent_){
            super(parent_);
        }
    }
    
    public static class UglyDuckling extends Egg{
        public UglyDuckling(Chicken parent_){
            super(parent_);
        }
    }

    public static void main (String[] args){
        Chicken momma = new Chicken(
        //  new YellowChick(), new BrownChick(), new UglyDuckling()  /* How can these objects be initialized properly? */
        );
    }

}

Aucun commentaire:

Enregistrer un commentaire