java - Give a reference to forming object from created object -
what best way following:
i have class a, creates , holds objects class b. object of class b doing own things, , has call method of parent object (of class a). heard not best idea hold reference of object in object b (idea shown in code snippet).
class a{ private b objectb; public a(){ objectb = new b(this); } public void methoda(){ // [...] } } class b{ private objecta; public b(a objecta){ this.objecta = objecta; } public void methodb(){ // [...] stuff objecta.methoda(); } }
is bad approach this? there better way?
as far can see class b acts sort of proxy or decorator difference , b don't share common interface. if design requires class b act (proxy, decorator, ...) best way define common interface: b implements a's interface , can "impersonate" it: in these cases, sharing reference "proxyed" class not bad, required. e.g.:
public interface { void methoda(); } public class aimpl implements { @override public void methoda() { /* .... */ } } public class aproxy implements { private final a; // use interface not implementation public aproxy(final a) { this.a = a; } @override public void methoda() { /* .... */ a.methoda(); /* .... */ } }
the other approach define hierarchy in parent of b b "needs" know work, or conversely , b have 1 1 e-r dependency: can follow composite design pattern - abused on orm techniques - or dependency injection pattern. in orm techniques parents , children have reference of each other act independently each other.
// might @entity public class { private b child; /* setter , getter */ } // might @entity public class b { private parent; /* setter , getter */ }
in dependency injection have options enforce relationship using class private final field , constructor parameter (more or less did) or using private field , setter.
public interface { void methoda(); } public class aimpl implements { @override void methoda() { /* .... */ } } public class b { // b not implement a! private final a; // use interface not implementation public b(final a) { this.a = a; } public void methodb() { /* ... */ } }
or
public class b { // b not implement a! private a; // use interface not implementation , not final /* setter , getter */ }
it not matter of whether bad or not share reference of parent/external object, depends on design requires , have model application accordingly. in first example b implements a's interface, b acts while in latter b not implement a's interface , depends on a: there's subtle important difference.
Comments
Post a Comment