Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hello, design pattern question...

 
Carmen Brianick
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a question about interfaces. I've read in HFSJ Design Patterns chapter that one of the code design goals is to have loosely coupled code, where for example if code A wants to use code B, then there should be an interface between them. Code B would implement this interface so that Code A would use the interface to communicate with code B methods.

I think this is what the statement means:

Interface called TestInterface would contain a sample method like:
public int addNumbers(int a, int b);

Code B would implement TestInterface, so it would have same method:
public int addNumbers(int a, int b){ return a + b; }

*** Please excuse any wrong syntax.

1.) My question is, is the below what is meant by "Code A would use the interface to communicate with code B methods."?
TestInterface inter = new B();
inter.addNumbers(2,3);

2.) If my interpretation is wrong, can you please provide a simple code example of this?

3.) If my interpretation is true, then why would I need an interface, can't I just do something like:
B bObj = new B();
b.addNumbers(2,3);

Thanks so much for your help! I've been hammering this for some time with no luck!

-Carmen
 
Gab Buda
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Carmen,

Since the "code A" uses an interface to access "code B", it will NOT have directly access to code B; it uses only the interface's methods. So, instead of

TestInterface inter = new B();

you'll use:

TestInterface inter = SomeFactoryClass.getInstance();

and in the method getInstance() you will create an object having the type B. When you'll decide to replace "code B" with another implementation ("code C" which also implements TestInterface), all that you'll need to do is to change the factory's method implementation (it will create and return a "code C" instance).

Hope this helps
Gabb

[ April 02, 2006: Message edited by: gabb buda ]
[ April 02, 2006: Message edited by: gabb buda ]
 
Carmen Brianick
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi gabb! Thanks so much for your great explaination. I'll take some time to think through too!

Thanks again,
Carmen
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic