I'm studying Visitor Pattern advantages, and quoting Design Patterns:
But an iteratorcan't work across object structures with different
types of elements. Forexample, the Iterator interface defined on page
295 can access only objects of type Item:
template <class Item>
clas Iterator { // ... Item CurrentItem() const; };
This implies that all elements the iterator can visit have a common parentclass Item.
Visitor does not have this restriction...
class Visitor {
public:
// ...
void VisitMyType(MyType*);
void VisitYourType(YourType*);
};
MyType and YourType do not have to be related throughinheritance at
all.
I agree about this quote, but I can't figure out an example where the Visitor Pattern could explore a structure (like a List) where objects collected in it are not related by a super class.
In other words, can you show me an example where the features above is true please?
First, you should know what these patterns are for.
The Iterator Pattern is used to access an aggregate sequentially without exposing its underlying representation. So you could Hide a List or array or similar aggregates behind an Iterator.
Visitor Pattern is used to perform an action on a structure of elements without changing the implementation of the elements themselves.
So you use the patterns in two different situations and not as alternatives to each other.
In the Visitor Pattern you implement an Interface IAcceptor in each element you want to visit. So the Visitor Pattern doesn't rely on a superclass but on Interfaces
public interface IAcceptor
{
public void Accept(IVisitor visitor);
}
So if you have a List of objects you can iterate over it and visit the objects implementing IAcceptor
public VisitorExample()
{
MyVisitorImplementation visitor = new MyVisitorImplementation();
List<object> objects = GetList();
foreach(IAcceptor item in objects)
item.Accept(visitor);
}
public interface IVisitor
{
public void Visit(MyAcceptorImplementation item);
public void Visit(AnotherAcceptorImplementation item);
}
public class MyAcceptorImplementation : IAcceptor
{
//Some Code ...
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
To complete the code here is Visitor to write to Console if it visits my or another implementation of an acceptor.
public class MyVisitorImplementation : IVisitor
{
public void Visit(MyAcceptorImplementation item)
{
Console.WriteLine("Mine");
}
public void Visit(AnotherAcceptorImplementation item)
{
Console.WriteLine("Another");
}
}
For more useful examples and better explanation have a look at Visitor Pattern and Iterator Pattern
EDIT: Here an example using both, the visitor and Iterator. The iterator is just the logic how to move through your aggregate. It would make more sense with a hierarchical structure.
public VisitorExample2()
{
MyVisitorImplementation visitor = new MyVisitorImplementation();
List<object> myListToHide = GetList();
//Here you hide that the aggregate is a List<object>
ConcreteIterator i = new ConcreteIterator(myListToHide);
IAcceptor item = i.First();
while(item != null)
{
item.Accept(visitor);
item = i.Next();
}
//... do something with the result
}
There are two good examples I know of where visitor is clearly preferable to iterator.
The first is interacting with some unknown set of class members, in particular in C++. For example, here's a visitor that prints out all the members of other classes. Imagine you're the author of Printer and someone you're unacquainted with is the author of Heterogeneous3Tuple.
#include <iostream>
template<class ElemType1, class ElemType2, class ElemType3>
class Heterogeneous3Tuple
{
public:
Heterogeneous3Tuple(ElemType1 elem1, ElemType2 elem2, ElemType3 elem3)
: elem1_(std::move(elem1)), elem2_(std::move(elem2)), elem3_(std::move(elem3))
{}
template<class Visitor>
void accept(const Visitor& visitor)
{
visitor(elem1_);
visitor(elem2_);
visitor(elem3_);
}
private:
ElemType1 elem1_;
ElemType2 elem2_;
ElemType3 elem3_;
};
class Printer
{
public:
template<class VisitedElemType>
void operator()(const VisitedElemType& visitee) const
{
std::cout << visitee << std::endl;
}
private:
};
int main() {
Heterogeneous3Tuple<char, int, double> h3t('a', 0, 3.14);
Printer p;
h3t.accept(p);
}
a
0
3.14
coliru
There's no sensible way to get an iterator to work here. Without even knowing what types our Printer class might interact with this works so long as the visitor is accept()ed and the elements all interact in a similar way with operator << and a stream.
The other good example I know of shows up in abstract syntax tree manipulations. CPython and LLVM both use visitors. Using a visitor here prevents code that manipulates certain AST nodes from needing to know how to iterate over all the various AST nodes that might branch in complicated ways. The LLVM source code goes into more detail. Here's the highlight:
/// Instruction visitors are used when you want to perform different actions
/// for different kinds of instructions without having to use lots of casts
/// and a big switch statement (in your code, that is).
///
/// To define your own visitor, inherit from this class, specifying your
/// new type for the 'SubClass' template parameter, and "override" visitXXX
/// functions in your class. I say "override" because this class is defined
/// in terms of statically resolved overloading, not virtual functions.
///
/// For example, here is a visitor that counts the number of malloc
/// instructions processed:
///
/// /// Declare the class. Note that we derive from InstVisitor instantiated
/// /// with _our new subclasses_ type.
/// ///
/// struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
/// unsigned Count;
/// CountAllocaVisitor() : Count(0) {}
///
/// void visitAllocaInst(AllocaInst &AI) { ++Count; }
/// };
///
/// And this class would be used like this:
/// CountAllocaVisitor CAV;
/// CAV.visit(function);
/// NumAllocas = CAV.Count;
Related
Suppose I have a game, where there are buildings sorted by type. Each type is represented as a separate class, but sometimes I have to do some uncommon logic for the buildings of the same type. How could one implement this kind of behaviour?
For example, I can identify buildings by ID, so I can have a giant switch or command pattern inside the building type class. But I think that something is not right with this approach.
Another approach is to have different class for any divergent logic. But this proposes a lot of small classes.
This is what polymorphism aims to solve, and one of the big differences between procedural and oop programming. You can achieve it through extending a base class, or by implementing an interface. Here is extending a base class:
public abstract class Building {
abstract void destroy();
}
public BrickBuilding extends Building {
#Override
public void destroy() {
bricks.fallToGround();
}
}
public HayBuilding extends Building {
#Override
public void destroy() {
straw.blowInWind();
}
}
In places in your code where you would have used a switch statement to switch on building type, just hold a reference to the abstract Building type, and call method destroy() on it:
public class BuildingDestroyer {
public void rampage() {
for(Building building : allTheBuildings) {
// Could be a BrickBuilding, or a HayBuilding
building.destroy();
}
}
}
Or, to address your concern about having a lot of small types, you can 'inject' a destroy behaviour you want into a common building type, like so...albeing, you will end up with a lot of different destroy behaviour classes too...so, this might not be a solution.
public interface DestroyBehaviour {
void destroy(Building building);
}
public class Building {
private int id;
public DestroyBehaviour destroyBehaviour;
public Building(int id, DestroyBehaviour destroyBehaviour) {
this.id = id;
this.destroyBehaviour = destroyBehaviour;
}
public void destroy() {
destroyBehaviour.destroy(this); // or something along those lines;
}
}
You can get rid of the giant switch by having a BuildingFactory class which exposes a registerBuildingType(typeName, instanceCreatorFunc) method, that each building class calls (from a static initialize method for example) and that gets called with a unique string for that class (class name would suffice) and a static "create" method that returns a new instance.
This approach also has the advantage of being able to load new buildings from dynamically linked libraries.
I'm having problems understanding the difference between the use of Interfaces and abstract classes.
For example, please see the following UML diagramm:
What is the difference between these two?
I'll provide an explanation with code and a shorter explanation. If you don't want to read, just skip to the "plain English explanation" below.
Explanation with code
In C++ terms an abstract class is a class which implement some methods but don't implement other methods. That means: you can use some of their methods, but you'll have to implement the non-implemented ones.
Interfaces are pure classes in C++, that is, a class which doesn't implement anything and you must implement everything if you want your class to be conformant to that interface.
E.g. - try this out with the link below
#include <iostream>
using namespace std;
// Shape is abstract class: some methods are already available, some are not
class Shape
{
public:
// This is already implemented and ready for polymorphism
virtual void area() { cout<<"Shape area"<<endl;}
// You MUST implement this
virtual void implement_me() = 0;
};
class Circle : public Shape
{
public:
virtual void area() { cout<<"Circle area"<<endl;}
void implement_me() { cout<<"I implemented it just because I had to"<<endl;}
};
class HalfCircle : public Circle
{
public:
virtual void area() { cout<<"HalfCircle area"<<endl;}
};
// ShapeInterface is a pure class or interface: everything must be implemented!
class ShapeInterface
{
public:
virtual void area() = 0;
};
class CircleFromInterface : public ShapeInterface
{
public:
// You MUST implement this!
virtual void area() { cout<<"CircleFromInterface area from interface"<<endl;};
};
int main() {
Shape* ptr_to_base = new HalfCircle();
ptr_to_base->area(); // HalfCircle area, polymorphism
ptr_to_base->Shape::area(); // Shape area
ptr_to_base->implement_me(); // from Circle
ShapeInterface *ptr_to_base_int = new CircleFromInterface();
ptr_to_base_int->area(); // Just the derived has it
return 0;
}
http://ideone.com/VJKuZx
Plain-English Explanation
If you want the over-simplified version:
Interfaces are usually "contracts" which you need to adhere in toto: you need to agree with everything and implement everything or it doesn't work.
Abstract classes are partial-contracts, there are some things which you must agree/implement, but there's also some other stuff which is already there and you can choose whether to re-implement it (override) or just be lazy and use the existing ones.
Abstract classes used for dealing with code duplication between subclasses, because they can share common logic and data. Interfaces just define common contract of implementors.
So, if there is no common implementation to share, then use interface (I always start with interface). If some common implementation will appear, then extract abstract base class and move common code there. But even in this case I keep interface in hierarchy, because it's easy to mock and it is more abstract, which allows other classes not depend on any implementation at all.
In your case I think Circle and HalfCircle share some implementation. So I would go with moving common code to Circle and inheriting HalfCircle from itŠ–
public class Circle : IShape
{
public double Radius { get; set; }
public virtual double Area
{
get { return Math.PI * Radius * Radius; }
}
}
public class HalfCircle : Circle
{
public override double Area
{
get { return base.Area / 2; }
}
}
If all shapes share some data or logic for calculating area, then it makes sense to declare base abstract Shape class for this common code. But if you will look at area calculation of square, there is nothing common with circle:
public class Square : IShape
{
public double Side { get; set; }
public double Area
{
get { return Side * Side; }
}
}
So IShape interface would be enough, because classes share only contract:
public interface IShape
{
double Area { get; }
}
An inheritance relationship, potentially using an abstract class, can usually be described as 'is a' and the implementation of an interface is a 'can be'. This concept can help when choosing which to use.
So if a Square 'is a' shape then inheritance would be an acceptable way of modelling this relationship.
Furthermore, an abstract class will give you the ability to provide common features. Where as an interface cannot contain any implementation.
I have a code (in C++, but for other languages solution of problem is probably similar):
namespace details {
struct C {
/// Documentation for common method.
void c();
};
};
/// Documentation for class A
struct A: public details:C {
/// Documentation for method a
void a();
};
/// Documentation for class B
struct B: public details:C {
/// Documentation for method b
void b();
};
And I want to hide class C (and whole details namespace) in documentation (it exists only to make A and B implementation shorter). But I need to have A and B in documentation, with c member (and all other members inherited from C) documented, like for source:
/// Documentation for class A
struct A {
/// Documentation for method a
void a();
/// Documentation for common method.
void c();
};
/// Documentation for class B
struct B {
/// Documentation for method b
void b();
/// Documentation for common method.
void c();
};
How to do this properly?
Say I am writing a user interface for a hardware accessory. There are two versions of the accessory - let's say Widget Lite and Widget Pro.
Widget Pro can do everything that Widget Lite can do, but with a few more options and can do a few things that Widget Lite can't. In more detail, Widget Lite has one channel, widget Pro has two, so when it comes to something analogous to volume control, I need only one control for the Lite, but two for the Pro allowing independent control.
In my first attempt at building an application to handle this, I had the class representing Widget Pro extend Widget Lite, but then I've ended up with all sorts of conditional cases to handle the differences which seems ugly. Does anyone know a suitable design pattern to help with such a situation? My imagination is drawing a blank in coming up with synonymous situations that might help in my search.
I would start off by looking at the plug in pattern (one of the forms of Dependency Inversion).
Try and abstract an interface common to the Lite and Pro versions, e.g.
interface IBaseWidget
{
IControl CreateVolumeControl();
// ... etc
}
In separate assemblies / dlls, implement your Lite and Pro widgets:
class LiteWidget : IBaseWidget
{
int _countCreated = 0;
IControl CreateVolumeControl()
{
_countCreated++;
if (_countCreated > 1)
{
throw new PleaseBuyTheProVersionException();
}
}
}
Since you don't want to distribute the Pro version with the Lite deployment, you will need to load the dlls at run time, e.g. by Convention (e.g. Your base app Looks around for DLL's named *Widget.dll), or by Configuration, which finds the applicable concrete implementation of IBaseWidget. As per #Bartek's comment, you ideally don't want your base engine classfactory to 'know' about specific concrete classes of IBaseWidget.
Visitor pattern might be useful for you. Check dofactory.
Visitor class...
...declares a Visit operation for each class of ConcreteElement in the
object structure. The operation's name and signature identifies the
class that sends the Visit request to the visitor. That lets the
visitor determine the concrete class of the element being visited.
Then the visitor can access the elements directly through its
particular interface
This is similar to Abstract class implementation as told by Vikdor.
Here is a wiki link for this.
The visitor pattern requires a programming language that supports
single dispatch and method overloading.
I have provided a very simple implementation using the visitor pattern for your requirement of different channels and volume settings for WidgetLite and Pro. I have mentioned in comments where the visitor pattern will greatly help you in reducing the if-else calls.
The basic philosophy is that you pass the control (ex. volume) to the widget and it will know how to use it as required. Hence, control object itself has a very simplified implementations. Each widget's code remains together!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WidgetVisitor
{
//This is the widget interface. It ensures that each widget type
//implements a visit functionality for each control. The visit function
//is overloaded here.
//The appropriate method is called by checking the parameter and this
//avoids the if-then logic elegantly
public interface Widget
{
void visit(Volume vol);
void visit(Channel chan);
void Display(AllControls ac);
}
//This is the interface which defines the controls. Each control that
//inherits this interface needs to define an "accept" method which
//calls the appropriate visit function of the right visitor,
//with the right control parameter passed through its call!
//This is how the double dispatch works.
//Double dispatch: A mechanism that dispatches a function call to different concrete
//functions depending on the runtime types of two objects involved in the call.
public interface WidgetControls
{
void accept(Widget visitor);
}
//I have implemented the volume control and channel control
//Notice how the code for defining each control is the SAME
//in visitor pattern! This is double dispatch in action
public class Volume : WidgetControls
{
public int volLevel { get; set; }
public int volJazz { get; set; }
public int volPop { get; set; }
public void accept(Widget wc)
{
wc.visit(this);
}
}
public class Channel : WidgetControls
{
public int channelsProvided { get; set; }
public int premiumChannels { get; set; }
public void accept(Widget wc)
{
wc.visit(this);
}
}
//Widget lite implementation. Notice the accept control implementation
//in lite and pro.
//Display function is an illustration on an entry point which calls the
//other visit functions. This can be replaced by any suitable function(s)
//of your choice
public class WidgetLite : Widget
{
public void visit(Volume vol)
{
Console.WriteLine("Widget Lite: volume level " + vol.volLevel);
}
public void visit(Channel cha)
{
Console.WriteLine("Widget Lite: Channels provided " + cha.channelsProvided);
}
public void Display(AllControls ac)
{
foreach (var control in ac.controls)
{
control.accept(this);
}
Console.ReadKey(true);
}
}
//Widget pro implementation
public class WidgetPro : Widget
{
public void visit(Volume vol)
{
Console.WriteLine("Widget Pro: rock volume " + vol.volLevel);
Console.WriteLine("Widget Pro: jazz volume " + vol.volJazz);
Console.WriteLine("Widget Pro: jazz volume " + vol.volPop);
}
public void visit(Channel cha)
{
Console.WriteLine("Widget Pro: Channels provided " + cha.channelsProvided);
Console.WriteLine("Widget Pro: Premium Channels provided " + cha.premiumChannels);
}
public void Display(AllControls ac)
{
foreach (var control in ac.controls)
{
control.accept(this);
}
Console.ReadKey(true);
}
}
//This is a public class that holds and defines all the
//controls you want to define or operate on for your widgets
public class AllControls
{
public WidgetControls [] controls { get; set; }
public AllControls(int volTot, int volJazz, int volPop, int channels, int chanPrem)
{
controls = new WidgetControls []
{
new Volume{volLevel = volTot, volJazz = volJazz, volPop = volPop},
new Channel{channelsProvided = channels, premiumChannels = chanPrem}
};
}
}
//finally, main function call
public class Program
{
static void Main(string[] args)
{
AllControls centralControl = new AllControls(3, 4, 2, 5, 10);
WidgetLite wl = new WidgetLite();
WidgetPro wp = new WidgetPro();
wl.Display(centralControl);
wp.Display(centralControl);
}
}
}
I would do it as follows:
AbstractWidget (Abstract class)
/\
/ \
/ \
/ \
/ \
WidgetLite WidgetPro
The common code would go into the AbstractWidget (abstract because, it shouldn't be instantiated) and the behaviour that is different between these two classes would go into the concrete classes.
I would strongly suggest that you have a base Widget class which both Widget Lite and Widget Pro derive from.
public class Widget {}
public class WidgetLite : Widget {}
public class WidgetPro : Widget {}
Have the properties/methods which are shared by both Pro and Lite inside the base class. This is a much cleaner design for you.
I am looking for an elegant design for a problem analogous to the following:
A story can have a flexible hierarchical structure. It might consist of several books, each of which have chapters, each of which have sections, each of which contain text. Or, it might simply have sections (a short story for instance). Or it might just consist of chapters that have sections. In all situations, you mustn't be allowed to mix styles (so you couldn't add a chapter to a story based on books, you would have to add the chapter to the book itself).
I have come up with a couple of design solutions for this type of problem but they get messy. Is there a clean way to represent this so that, given a reference to a Story class I can get access to the content in a clear, systematic fashion?
Its kind of tricky situation because the concepts like "Books", "chapters", "sections", may have some common elements that suggest a class hierarchy or common interface implementation.
And at the same time, enough different to be handle as different classes / objects, at all, as the requirement of "so you couldn't add a chapter to a story based on books".
When dealing conceptualy with hierarchical objects, there are several approaches of how to turn them into into code, each one suits better to a particular situation.
1. Class Composition
There is a class or prototype for each concept, they may be related or not by inheritance or interfaces.
There are internal collections of the elements, and their operations can be restricted,
by methods.
// this one can be optional, not required,
// replaced by several parent classes,
// or replaced by interfaces
public class LibraryRootClassMaybe {
// members here
}
public class BookText extends LibraryRootClassMaybe {
// members here
} // class BookText
public class BookSection extends LibraryRootClassMaybe {
// element collection should not be public
List BookTexts;
public Book() {
this.BookTexts = new ArrayList();
}
public void addBookTest(BookText Item) {
// validation and casting from object to BookText
}
// members here
} // class BookSection
public class BookChapter extends LibraryRootClassMaybe {
// element collection should not be public
List BookSections;
public Book() {
this.BookSections = new ArrayList();
}
public void addBookTest(BookSection Item) {
// validation and casting from object to BookSection
}
// members here
} // class BookChapter
public class Book extends LibraryRootClassMaybe {
// element collection should not be public
List BookChapters;
public Book() {
this.BookChapters = new ArrayList();
}
public void addBookTest(BookText Item) {
// validation and casting from object to BookText
}
// members here
} // class Book
These approach is good when there are not many different classes, maybe 5.
2. The Tree Design Pattern.
These one applies when all elements will be equal if not similar,
usually same class or interface, usually a lot of items.
These one does not apply to your case, but,
I had to mention, to apply better.
Usually, a tree / hierarchical collection class, its used.
It could be a subclass of a generic / template tree collection,
or a subclass of a base tre collection,
that is intended to be replaced by child classes with particular members.
public class FileSystemRootClass {
public bool AmISystemRoot() {
// more
}
public bool AmIAFolder() {
// more
}
public bool AmIAFile() {
// more
}
public void addSystemRoot(string FileSystemName) {
// more
}
public void addFolder(string FileSystemName) {
// more
}
public void addFile(string FileSystemName) {
// more
}
// members here
}
3. The Hybrid.
These one is a combination of the previous two,
its used when there is a lot of related items,
its more complex, may use or not the Factory & Abstract Factory Patterns,
and its more common example are visual controls & widgets libraries.
import java.util.*;
public class WidgetsExample {
public static void main(String[] args) {
TreeSet <Widget> FormControls = new TreeSet<Widget>();
TextBoxWidget TextBox = new TextBoxWidget();
FormControls.add(TextBoxWidget);
ListBoxWidget ListBox = new ListBoxWidget();
FormControls.add(TextBoxWidget);
ButtonWidget Button = new ButtonWidget();
FormControls.add(Button);
} // class WidgetsExample
You may notice that I didn't use the "factory pattern" & "abstract factory",
due to require more code.
Good Luck.
Good OO design starts with thinking about Use Cases and not class hierarchies. This is a common mistake and tends to produce over-complicated designs.
First consider what you are building and write out a problem statement a description of the problem you are solving using English prose in the language of the problem domain.
Then consider making a mockup if the product is a UI.
Then you can start writing out use cases and start thinking about how objects will interact with each other.
It's called Object-oriented programming, not Class-oriented programming. Classes are the specification in code to manage/create/run all the objects in the system. I'd be thinking about objects and what they are doing. Classes are simply an implementation detail.
If your goal is to perform operations on hierarchies, you might want to consider using the Composite pattern. You could do something like have a Story object that can contain a list of Story objects. Each Story object would also have it's own type (book-collection,book,chapter,sub-chapter,paragraph,essay), and it's own attributes and methods (depending on your use cases).
I'd try something like this:
interface StoryElement<SE extends SubElements>{
List<SE> getContents()
}
class Story<T extends StoryElement>
class Book implements StoryElement<Chapter> ...
class Chapter implements StoryElement<Section> ...
class Section implements StoryElement<Text>
class Text implements StoryElement<Text> {... // ugly hack, don't know of a clean way to end the recursion with Java Generics
Now you can have a Story of Books or a Story of Text.
Warning: Java Generics tend to fall flat on their face when trying to complex things. In case of doubt, just forget generics and cast.
Thanks to all the posters. Here is my work-in-progress solution:
public abstract class Element
{
public ElementSet getContent() { return content; }
// Overrides of setContent() check to see if the content type is appropriate
// using instanceof.
public void setContent( ElementSet content )
{
this.content = content;
}
private ElementSet content;
}
public abstract class ElementSet
{
protected final void addElement( Element e )
{
elements.add(e);
}
private final List<Element> elements = new ArrayList<Element>();
}
public class BookSet extends ElementSet
{
// Typesafe interface.
public void addBook( Book book ) { super.addElement( book ); }
}
public class ChapterSet extends ElementSet { /* similar to BookSet */ }
public class SectionSet extends ElementSet { /* similar to BookSet */ }
public class Book extends Element
{
#Override
public void setContent( ElementSet content )
{
if ( !(content instanceof ChapterSet) && !(content instanceof SectionSet) )
{
throw new RuntimeException();
}
super.setContent( content );
}
public boolean addChapter( Chapter chapter )
{
ElementSet content = getContent();
if ( content == null )
{
content = new ChapterSet();
setContent( content );
}
else if ( !(content instanceof ChapterSet) )
{
// Structure is wrong.
return false;
}
ChapterSet chapters = (ChapterSet)content;
chapters.addChapter( chapter);
return true;
}
public boolean addSection( Section section )
{
ElementSet content = getContent();
if ( content == null )
{
content = new SectionSet();
super.setContent( content );
}
else if ( !(content instanceof SectionSet) )
{
// Structure is wrong.
return false;
}
SectionSet sections = (SectionSet)content;
sections.addSection( section );
return true;
}
}
public class Chapter extends Element
{
#Override
public void setContent( ElementSet content )
{
if ( !(content instanceof SectionSet) )
{
throw new RuntimeException();
}
super.setContent( content );
}
public boolean addSection( Section section )
{
ElementSet content = getContent();
if ( content == null )
{
content = new SectionSet();
super.setContent( content );
}
else if ( !(content instanceof SectionSet) )
{
// Structure is wrong.
return false;
}
SectionSet sections = (SectionSet)content;
sections.addSection( section );
return true;
}
}
I tried using generics to achieve the same end, but it looked rather ugly due to need to reflect the parametrised type of a container.