making a class with abstraction is also encapsulation? - java

Encapsulation is said to be wrapping up of data and method and hidding functionality(method and instance variable) that is not needed for outside of this object
my question is only making a variable private and public is encapsulation ? or making a class with abstraction is also encapsulation ?
For Example:
I have Switch(Electic Switch) class doing on or off
to make a Switch class i have used abstraction
and i encapsulated Switch class with using abstraction so that i can map
motor or bulb or any electric Instrument
public class Switch {
private boolean isOff = true;
private ISwitchListener listener;
public Switch(ISwitchListener listener) {
this.listener = listener;
}
public void trigger() {
isOff = !isOff;
if(isOff) {
listener.off();
} else {
listener.on();
}
}
}
public class Bulb implements ISwitchListener {
#Override
public void on() {
// TODO Auto-generated method stub
System.out.println("bulb is glittering");
}
#Override
public void off() {
// TODO Auto-generated method stub
System.out.println("bulb is not glittering");
}
}
public interface ISwitchListener {
public void on();
public void off();
}
public class Executor {
public static void main(String[] args) {
// TODO Auto-generated method stub
Switch swt = new Switch(new Bulb());
swt.trigger();
}
}
if i am not using abstraction here , i would have class like below
public class Switch {
private boolean isOff = true;
public void trigger() {
isOff = !isOff;
Bulb b =new Bulb();
if(isOff) {
b.off();
} else {
b.on();
}
}
}
When i want to map Motor to Switch i need to change class as bleow
public class Switch {
private boolean isOff = true;
public void trigger() {
isOff = !isOff;
Bulb b =new Bulb();
if(isOff) {
b.off();
} else {
b.on();
}
}
}
public class Motor {
public void on() {
// TODO Auto-generated method stub
System.out.println("Motor is rotating");
}
public void off() {
// TODO Auto-generated method stub
System.out.println("Motor is getting off to rotate");
}
}

In general, no, abstraction and encapsulation are two different things. Specifically, abstraction means removing detail that is unnecessary for the intended purpose of the code or model. For example, if you write a program to calculate how much paint you need for a house, your model of a house needs to include the surface area, but doesn't need to include the address, or the size of the yard.
Encapsulation means hiding the internal workings of an object or module, such that the coupling between objects can be controlled and readily changed. If there were no encapsulation, clients of the object might directly reference its internal elements, which would mean that you would have to change all the clients if you modified the object.
Regarding the code example, I think a better solution would be to create an interface "Switchable" and have Motor and Bulb implement it. Like so:
public interface Switchable {
void on();
void off();
}
public class Motor implements Switchable {
public void on() {
System.out.println("Motor is rotating");
}
public void off() {
System.out.println("Motor is getting off to rotate");
}
}
public class Switch {
private boolean isOff = true;
private Switchable switchable;
public Switch(Switchable switchable) {
this.switchable = switchable;
}
public void trigger() {
isOff = !isOff;
if(isOff) {
switchable.off();
} else {
switchable.on();
}
}
}
Hope that helps.

Your first example is an example for dependency injection => you let the caller decide which concrete class the class "Switch" needs to do its job.
In fact it is the "opposite" of data hiding as the outside world has to know some implementation details of the class "Switch". => it needs an implementation of ISwitchListener

As #T I said, it can be a method hiding for example from Java 8 you can create default implementation in the interface, so you can hide that in the class where implement the interface.
But encapsulation is about field (instance variable) hiding. Creating a private member (instance variable) and creating setter and getter. You will reach the value only via dedicated methods.
If you want to encapsulate your methods, you need to deal with accessibility (see default and protected modifiers).
So the answer for your question is: No. Making a class with abstraction is not encapsulation.

Abstraction and Encapsulation are interrelated. You can say Abstraction is needed to Encapsulate the system.
Abstraction is when a client system does not need to know more than what is in the interface.
Encapsulation is when a client of a module is not able to know more than what is in the interface.
Pleas refer this page for a beautiful article on this topic.

Related

Add another method to every implementation of my Interface in all implementations

I have an interface:
public interface InterfaceListener {
void eventEnd();
}
Some methods receives this InterfaceListener as a parameter and every one of course implement it on his own way. For example:
myObject.callMethod(false,InterfaceListener() {
#Override
public void eventEnd() {
//do some extra code
}
});
Now I want to add some changes, to insure that every implementation in eventEnd() will be called only after it's passed another method - callMyExtraMethod() that common to all the calls, something like that:
myObject.callMethod(false,InterfaceListener() {
#Override
public void eventEnd() {
if (callMyExtraMethod()) {
//do some extra code
}
}
});
Any ideas how can I add it to the logic without passing on every implementation and adding manually that same check to all?
Rename eventEnd to eventEndImpl in IDE. Then add default method:
public interface InterfaceListener {
default void eventEnd() {
if (callMyExtraMethod()) {
eventEndImpl();
}
}
void eventEndImpl();
// Uncomment, if this method must belong to the same class.
// bool callMyExtraMethod();
}
If you are using Java 7, one way to achieve this -
Create an AbstractListener class with abstract methods
eventEnd and callMyExtraMethod and a template method templateMethod
public abstract class AbstractListener {
public abstract void eventEnd();
public abstract boolean callMyExtraMethod();
public void templateMethod(){
if(callMyExtraMethod()){
eventEnd();
}
}
}
Now you can create the Anonymous classes and call the templateMethod(). This will ensure the callMyExtraMethod() check before invoking eventEnd()
AbstractListener listener = new AbstractListener() {
#Override
public void eventEnd() {
// your implementation
}
#Override
public boolean callMyExtraMethod() {
//System.out.println("I am callMyExtraMethod");
return true;
}
};
listener.templateMethod();
Hope this helps.

Java: Is it possible to always execute a certain function before other functions are called? (Like #Before in JUnit)

Is there a way to always execute a function before any other function of a class is called?
I have a class where I need to refresh some fields always before any function is called:
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.
JUnit has a solution for this with the #Before-Annotation. Is there a way to do this in other classes as well?
And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!
Use a dynamic proxy in which you can filter to those methods before which your specific "before" method should be called. And call it in those cases before dispatching the call. Please see the answer from How do I intercept a method invocation with standard java features (no AspectJ etc)?
UPDATE:
An interface is needed to be separated for the proxy. The refresh() method cannot remain private. It must be public and part of the interface (which is not nice here) to be able to be called from the proxy.
package CallBefore;
public interface ExampleInterface {
void function1();
void function2();
void otherFunction();
void refresh();
}
Your class implements that interface:
package CallBefore;
public class Example implements ExampleInterface {
#Override
public void function1() {
System.out.println("function1() has been called");
}
#Override
public void function2() {
System.out.println("function2() has been called");
}
#Override
public void otherFunction() {
System.out.println("otherFunction() has been called");
}
#Override
public void refresh() {
System.out.println("refresh() has been called");
}
}
The proxy which does the trick. It filters the needed methods and calls refresh().
package CallBefore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ExampleProxy implements InvocationHandler {
private ExampleInterface obj;
public static ExampleInterface newInstance(ExampleInterface obj) {
return (ExampleInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new ExampleProxy(obj));
}
private ExampleProxy(ExampleInterface obj) {
this.obj = obj;
}
#Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
if (m.getName().startsWith("function")) {
obj.refresh();
}
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return result;
}
}
The usage:
package CallBefore;
public class Main {
public static void main(String[] args) {
ExampleInterface proxy = ExampleProxy.newInstance(new Example());
proxy.function1();
proxy.function2();
proxy.otherFunction();
proxy.refresh();
}
}
Output:
refresh() has been called
function1() has been called
refresh() has been called
function2() has been called
otherFunction() has been called
refresh() has been called
This may not solve your exact problem but at least could be a starting point if you are allowed considering a re-design. Below is a simple implementation but with some small touches I believe you can achieve a more elegant solution. BTW, this is called Dynamic Proxy Pattern.
First thing you need is an interface for your class.
public interface Interface {
void hello(String name);
void bye(String name);
}
public class Implementation implements Interface {
#Override
public void hello(String name) {
System.out.println("Hello " + name);
}
#Override
public void bye(String name) {
System.out.println("Bye " + name);
}
}
Then java.lang.reflect.Proxy class comes to help. This class is able to create an instance for a given interface at runtime. It also accepts an InvocationHandler which helps you to capture method calls and looks like this.
public class InvocationHandlerImpl implements InvocationHandler {
private final Object instance;
public InvocationHandlerImpl(Object instance) {
this.instance = instance;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
System.out.println("Before");
result = method.invoke(instance, args);
System.out.println("After");
} catch (Exception e){
e.printStackTrace();
throw e;
} finally {
System.out.println("finally");
}
return result;
}
}
After all your client code will look like this.
Interface instance = new Implementation();
Interface proxy = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandlerImpl(instance));
proxy.hello("Mehmet");
proxy.bye("Mehmet");
Output for this code is
Before
Hello Mehmet
After
finally
Before
Bye Mehmet
After
finally
I would define getters for every field and do the refreshment inside the getter. If you want to avoid unrefreshed access to your private fields at all, put them in a superclass (together with the getters which call refresh).
Depending on your project structure, it may be also sensible to introduce a separate class for all data that is regularly refreshed. It can offer getters and avoid that anyone accesses the non-refreshed fields.
Not in Java SE, but if you are using Java EE, you could use interceptors.
For standalone applications, you could consider using a bytecode manipulation framework, like javassist.
You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
protected int getData(){
refresh();
return data;
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
It is better to write another method which will be made protected(accessible to the child classes) which will call first the refresh method and then call the function.
This way the data would be refreshed before the function is called everytime(As per your requirement).
eg:
protected void callFunction1(){
refresh();
function();
}
Thanks,
Rajesh
You should use Decorator in this case. Decorator is a good choice for something like interceptor. Example here: https://msdn.microsoft.com/en-us/library/dn178467(v=pandp.30).aspx

How would I go about implementing this Java interface?

I am currently in the design mode for this problem:
Implement the Speaker interface that is predefined. Create three classes that implement Speaker in various ways. Create a driver class whose main method instantiates some of these objects and tests their abilities.
How would I go about designing this program and them moving into the coding stage. I want to use these three classes to implement the Speaker interface class: Politician, Lecturer, and Pastor class. The methods I want to use are:
public void speak();
public void announce (String str);
Now for my design and coding, how would I go about to declare and object reference variable and have that variable have multiple references?
It's simple really. In brief:
class ClassA implements Speaker
{
public void speak(){
System.out.println("I love Java") ; //implement the speak method
}
}
class ClassB implements Speaker //follow the example of ClassA
class ClassC implements Speaker //same as above
Speaker[] speakers = new Speakers{new ClassA(),new ClassB(),new ClassC()} ;
for(Speaker speaker: speakers)
speaker.speak(); //polymorphically call the speak() method defined in the contract.
See "What is an Interface?" http://docs.oracle.com/javase/tutorial/java/concepts/interface.html This will hopefully get you started with the basics you're looking for.
The start of the implementation would look something like the following...
class Politician implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
class Lecturer implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
class Lecturer implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
public static void main(String [] args)
{
Speaker s1 = new Politician();
Speaker s2 = new Pastor();
Speaker s3 = new Lecturer();
// Do something...
}
Use a Factory Method Design Pattern.. Check this article at http://en.wikipedia.org/wiki/Factory_method_pattern
Your code could look something like this, if you use the Factory pattern
public class SpeakerFactory {
enum SpeakerEnum { POLITICIAN, LECTURER, PASTOR} ;
Speaker getSpeaker(SpeakerEnum speakerType) {
switch (speakerType) {
case POLITICIAN : return new Politician();
....
}
}
}

How to overload a method with generic parameter in java? [duplicate]

I have FinanceRequests and CommisionTransactions in my domain.
If I have a list of FinanceRequests each FinanceRequest could contain multiple CommisionTransactions that need to be clawed back. Dont worry how exactly that is done.
The class below (very bottom) makes me feel all fuzzy and warm since its succint and reuses existing code nicely. One problem Type erasure.
public void clawBack(Collection<FinanceRequest> financeRequestList)
public void clawBack(Collection<CommissionTrns> commissionTrnsList)
They both have the same signature after erasure, ie:
Collection<FinanceRequest> --> Collection<Object>
Collection<CommissionTrns> --> Collection<Object>
So eclipse complainst that:
Method clawBack(Collection) has the same erasure clawBack(Collection) as another method in type CommissionFacade
Any suggestions to restructure this so that it still an elegant solution that makes good code reuse?
public class CommissionFacade
{
/********FINANCE REQUESTS****************/
public void clawBack(FinanceRequest financeRequest)
{
Collection<CommissionTrns> commTrnsList = financeRequest.getCommissionTrnsList();
this.clawBack(commTrnsList);
}
public void clawBack(Collection<FinanceRequest> financeRequestList)
{
for(FinanceRequest finReq : financeRequestList)
{
this.clawBack(finReq);
}
}
/********COMMISSION TRANSACTIOS****************/
public void clawBack(CommissionTrns commissionTrns)
{
//Do clawback for single CommissionTrns
}
public void clawBack(Collection<CommissionTrns> commissionTrnsList)
{
for(CommissionTrns commTrn : commissionTrnsList)
{
this.clawBack(commTrn);
}
}
}
Either rename the methods, or use polymorphism: use an interface, and then either put the clawback code in the objects themselves, or use double-dispatch (depending on your design paradigm and taste).
With code in objects that would be:
public interface Clawbackable{
void clawBack()
}
public class CommissionFacade
{
public <T extends Clawbackable> void clawBack(Collection<T> objects)
{
for(T object: objects)
{
object.clawBack();
}
}
}
public class CommissionTrns implements Clawbackable {
public void clawback(){
// do clawback for commissions
}
}
public class FinanceRequest implements Clawbackable {
public void clawBack(){
// do clwaback for FinanceRequest
}
}
I prefer this approach, since I'm of the belief your domain should contain your logic; but I'm not fully aware of your exact wishes, so I'll leave it up to you.
With a double dispatch, you would pass the "ClawbackHandler" to the clawback method, and on the handler call the appropriate method depending on the type.
I think your best option is to simply name the method differently.
public void clawBackFinReqs(Collection<FinanceRequest> financeRequestList) {
}
public void clawBackComTrans(Collection<CommissionTrns> commissionTrnsList) {
}
In fact, it's not too bad, since you don't get anything extra out of having the same name on them.
Keep in mind, that the JVM will not decide which method to call at runtime. As opposed to virtual methods / method overriding resolution of overloaded methods are done at compile time. The Java Tutorials on method overloading even points out that "Overloaded methods should be used sparingly...".
Here is a trick with overloading by the second varargs parameter for the CommissionFacade class from the question:
public class CommissionFacade {
public void clawBack(Collection<FinanceRequest> financeRequestList, FinanceRequestType ...ignore) {
// code
}
public void clawBack(Collection<CommissionTrns> commissionTrnsList, CommissionTrnsType ...ignore) {
// code
}
/*******TYPES TO TRICK TYPE ERASURE*******/
private static class FinanceRequestType {}
private static class CommissionTrnsType {}
}
The code snippet to fast-check this trick works:
import java.util.ArrayList;
class HelloType {
public static void main(String[] args) {
method(new ArrayList<Integer>());
method(new ArrayList<Double>());
}
static void method(ArrayList<Integer> ints, IntegerType ...ignore) {
System.out.println("Hello, Integer!");
}
static void method(ArrayList<Double> dbs, DoubleType ...ignore) {
System.out.println("Hello, Double!");
}
static class IntegerType {}
static class DoubleType {}
}

General OO question about inheritance and extensibility

So, in a single parent inheritance model what's the best solution for making code extensible for future changes while keeping the same interface (I'd like to emphasize the fact that these changes cannot be known at the time of the original implementation, the main focus of my question is to explore the best mechanism/pattern for supporting these changes as they come up)? I know that this is a very basic OO question and below I provide example of how I've been going about it, but I was wondering if there a better solution to this common problem.
Here's what I've been doing (the example code is in Java):
In the beginning, the following two classes and interface are created:
public class Foo
{
protected int z;
}
public interface FooHandler
{
void handleFoo(Foo foo);
}
public class DefaultFooHandler implements FooHandler
{
#Override
public void handleFoo(Foo foo)
{
//do something here
}
}
The system uses variables/fields of type FooHandler only and that object (in this case DefaultFooHandler) is created in a few, well-defined places (perhaps there's a FooHandlerFactory) so as to compensate for any changes that might happen in the future.
Then, at some point in the future a need to extend Foo arises to add some functionality. So, two new classes are created:
public class ImprovedFoo extends Foo
{
protected double k;
}
public class ImprovedFooHandler extends DefaultFooHandler
{
#Override
public void handleFoo(Foo foo)
{
if(foo instanceof ImprovedFoo)
{
handleImprovedFoo((ImprovedFoo)foo);
return;
}
if(foo instanceof Foo)
{
super.handleFoo(foo);
return;
}
}
public void handleImprovedFoo(ImprovedFoo foo)
{
//do something involving ImprovedFoo
}
}
The thing that makes me cringe in the example above is the if-statements that appear in ImprovedFooHandler.handleFoo
Is there a way to avoid using the if-statements and the instanceof operator?
First of all the code you wrote won't work.
Each time you see instanceof and if...else together be very careful. The order of these checks is very important. In your case you'll never execute handleImpovedFoo. Guess why :)
It's absolutely normal you have these instanceof statements. Sometimes it's the only way to provide different behavior for a subtype.
But here you can use another trick: use simple Map. Map classes of foo-hierarchy to instances of fooHandler-hierarchy.
Map<Class<? extends Foo>, FooHandler> map ...
map.put( Foo.class, new FooHandler() );
map.put( ImprovedFoo.class, new ImprovedFooHandler() );
Foo foo ...; // here comes an unknown foo
map.get( foo.getClass() ).handleFoo( foo );
The best way of handling this depends too much on the individual case to provide a general solution. So I'm going to provide a number of examples and how I would solve them.
Case 1: Virtual File System
Clients of your code implement virtual file systems which enable them to operate any sort of resource which can be made to look like a file. They do so by implementing the following interface.
interface IFolder
{
IFolder subFolder(String Name);
void delete(String filename);
void removeFolder(); // must be empty
IFile openFile(String Name);
List<String> getFiles();
}
In the next version of your software you want to add the ability to remove a directory and all it contents. Call it removeTree. You cannot simply add removeTree to IFolder because that will break all users of IFolder. Instead:
interface IFolder2 implements IFolder
{
void removeTree();
}
Whenever a client registers an IFolder (rather then IFolder2), register
new IFolder2Adapter(folder)
Instead, and use IFolder2 throughout your application. Most of your code should not be concerned with the difference about what old versions of IFolder supported.
Case 2: Better Strings
You have a string class which supports various functionality.
class String
{
String substring(int start, end);
}
You decide to add string searching, in a new version and thus implement:
class SearchableString extends String
{
int find(String);
}
That's just silly, SearchableString should be merged into String.
Case 3: Shapes
You have a shape simulation, which lets you get the areas of shapes.
class Shape
{
double Area();
static List<Shape> allShapes; // forgive evil staticness
}
Now you introduce a new kind of Shape:
class DrawableShape extends Shape
{
void Draw(Painter paint);
}
We could add a default empty Draw method to Shape. But it seems incorrect to have Shape have a Draw method because shapes in general aren't intended to be drawn. The drawing really needs a list of DrawableShapes not the list of Shapes that is provided. In fact, it may be that DrawableShape shouldn't be a Shape at all.
Case 4: Parts
Suppose that we have a Car:
class Car
{
Motor getMotor();
Wheels getWheels();
}
void maintain(Car car)
{
car.getMotor().changeOil();
car.getWheels().rotate();
}
Of course, you know somewhere down the road, somebody will make a better car.
class BetterCar extends Car
{
Highbeams getHighBeams();
}
Here we can make use of the visitor pattern.
void maintain(Car car)
{
car.visit( new Maintainer() );
}
The car passes all of its component parts to calls into ICarVisitor interface allowing the Maintainer class to maintain each component.
Case 5: Game Objects
We have a game with a variety of objects which can be seen on screen
class GameObject
{
void Draw(Painter painter);
void Destroy();
void Move(Point point);
}
Some of our game objects need the ability to perform logic on a regular interval, so we create:
class LogicGameObject extends GameObject
{
void Logic();
}
How do we call Logic() on all of the LogicGameObjects? In this case, adding an empty Logic() method to GameObject seems like the best option. Its perfectly within the job description of a GameObject to expect it to be able to know what to do for a Logic update even if its nothing.
Conclusion
The best way of handling this situations depends on the individual situation. That's why I posed the question of why you didn't want to add the functionality to Foo. The best way of extending Foo depends on what exactly you are doing. What are you seeing with the instanceof/if showing up is a symptom that you haven't extended the object in the best way.
In situations like this I usually use a factory to get the appropriate FooHandler for the type of Foo that I have. In this case there would still be a set of ifs but they would be in the factory not the implementation of the handler.
Yes, don't violate LSP which is what you appear to be doing here. Have you considered the Strategy pattern?
This looks like a plain simple case for basic polymorphism.Give Foo a method named something like DontWorryI'llHandleThisMyself() (um, except without the apostrophe, and a more sensible name). The FooHandler just calls this method of whatever Foo it's given. Derived classes of Foo override this method as they please. The example in the question seems to have things inside-out.
With the visitor pattern you could do something like this,
abstract class absFoo {}
class Foo extends absFoo
{
protected int z;
}
class ImprovedFoo extends absFoo
{
protected double k;
}
interface FooHandler {
void accept(IFooVisitor visitor, absFoo foo);
}
class DefaultFooHandler implements FooHandler
{
public void accept(IFooVisitor visitor, absFoo foo)
{
visitor.visit(this, foo);
}
public void handleFoo(absFoo foo) {
System.out.println("DefaultFooHandler");
}
}
class ImprovedFooHandler implements FooHandler
{
public void handleFoo(absFoo foo)
{
System.out.println("ImprovedFooHandler");
}
public void accept(IFooVisitor visitor, absFoo foo) {
visitor.visit(this, foo);
}
}
interface IFooVisitor {
public void visit(DefaultFooHandler fooHandler, absFoo foo);
public void visit(ImprovedFooHandler fooHandler, absFoo foo);
}
class FooVisitor implements IFooVisitor{
public void visit(DefaultFooHandler fHandler, absFoo foo) {
fHandler.handleFoo(foo);
}
public void visit(ImprovedFooHandler iFhandler, absFoo foo) {
iFhandler.handleFoo(foo);
}
}
public class Visitor {
public static void main(String args[]) {
absFoo df = new Foo();
absFoo idf = new ImprovedFoo();
FooHandler handler = new ImprovedFooHandler();
IFooVisitor visitor = new FooVisitor();
handler.accept(visitor, idf);
}
}
But this does not guarantee only Foo can be passed to DefaultFooHandler. It allows ImprovedFoo also can be passed to DefaultFooHandler. To overcome, something similar can be done
class Foo
{
protected int z;
}
class ImprovedFoo
{
protected double k;
}
interface FooHandler {
void accept(IFooVisitor visitor);
}
class DefaultFooHandler implements FooHandler
{
private Foo iFoo;
public DefaultFooHandler(Foo foo) {
this.iFoo = foo;
}
public void accept(IFooVisitor visitor)
{
visitor.visit(this);
}
public void handleFoo() {
System.out.println("DefaultFooHandler");
}
}
class ImprovedFooHandler implements FooHandler
{
private ImprovedFoo iFoo;
public ImprovedFooHandler(ImprovedFoo iFoo) {
this.iFoo = iFoo;
}
public void handleFoo()
{
System.out.println("ImprovedFooHandler");
}
public void accept(IFooVisitor visitor) {
visitor.visit(this);
}
}
interface IFooVisitor {
public void visit(DefaultFooHandler fooHandler);
public void visit(ImprovedFooHandler fooHandler);
}
class FooVisitor implements IFooVisitor{
public void visit(DefaultFooHandler fHandler) {
fHandler.handleFoo();
}
public void visit(ImprovedFooHandler iFhandler) {
iFhandler.handleFoo();
}
}
public class Visitor {
public static void main(String args[]) {
FooHandler handler = new DefaultFooHandler(new Foo());
FooHandler handler2 = new ImprovedFooHandler(new ImprovedFoo());
IFooVisitor visitor = new FooVisitor();
handler.accept(visitor);
handler2.accept(visitor);
}
}

Categories

Resources