Execute an objects method without making a new instance -
how can execute print within testobject?
class program { private int value; static void main() { testobject test = new testobject(); program p1 = new program(); program p2 = new program(); p1.value = 1; p2.value = 2; p1.print(); p2.print(); } private void print() { console.write(value.tostring()); console.readkey(); } } class testobject { // how execute p1.print here? }
there multiple ways this:
pass program directly testobject
pros:
- simple change
cons:
- you have make
printpublic - you expose other things in program
- you're coupling
testobjectprogramdirectly
here's sample code:
class program { static void main() { testobject test = new testobject(this); } public void print() { console.write(value.tostring()); console.readkey(); } } class testobject { public testobject(program p) { p.print(); } } pass delegate testobject
pros:
- simple change
- doesn't have make
printpublic - only exposes 1 method
testobject
cons:
- the coupling
testobjectwants something, nottestobjectwants access something
here's sample code:
class program { static void main() { testobject test = new testobject(() => print()); } private void print() { console.write(value.tostring()); console.readkey(); } } class testobject { public testobject(action print) { print(); } } implement interface in program , pass testobject
pros:
- only exposes interface exposes
- easier implement other places (better "need interface" "needs delegate", clearer contract specification)
- no coupling specific type, coupling any object meets criteria - implements interface
cons:
- none relevant (in opinion)
here's sample code:
interface iprintable { void print(); } class program : iprintable { static void main() { testobject test = new testobject(this); } public void print() { console.write(value.tostring()); console.readkey(); } } class testobject { public testobject(iprintable p) { p.print(); } } conclusion: advice pick interface way. clearer design, easier extend without having multiple delegates being passed around.
Comments
Post a Comment