Classes with template method design - java

I have made this four classes and I'm wondering if I used the template method design pattern correctly because I'm really struggeling with this subject.
I have used the methods getPrijsBehandeling() and getBeschrijvingBehandeling() as my abstract classes.
Also I'm wondering if I should use the abstract methods in my UML or only in the code.
Since this is the first time I'm using a design pattern I wonder if I’m on the right track.
public abstract class Behandeling {
private String beschrijving;
private double prijs;
private int behandelingsNummer;
private Wassen wassen;
public Behandeling(int behandelingsNummber, int keuze) {
this.behandelingsNummer = behandelingsNummber;
if(keuze == 3 || keuze == 4) {
wassen = new Wassen();
}
}
public abstract double getPrijsBehandeling();
public abstract String getBeschrijvingBehandeling();
public double getPrijs() {
prijs = getPrijsBehandeling();
if(wassen != null) {
prijs += wassen.getPrijsBehandeling();
}
return prijs;
}
public String getBeschrijving() {
beschrijving = getBeschrijvingBehandeling();
if(wassen != null) {
beschrijving += wassen.getBeschrijvingBehandeling();
}
return beschrijving;
}
public int getBehandelingsNummer() {
return behandelingsNummer;
}
}
------------------------------------------
public class Verven extends Behandeling {
public Verven(int behandelingsNummer, int keuze) {
super(behandelingsNummer, keuze);
}
#Override
public double getPrijsBehandeling() {
return 20;
}
#Override
public String getBeschrijvingBehandeling() {
return "Haren worden geverfd";
}
}
---------------------------------------------
public class Knippen extends Behandeling{
public Knippen(int behandelingsNummer, int keuze) {
super(behandelingsNummer, keuze);
}
#Override
public double getPrijsBehandeling() {
return 15;
}
#Override
public String getBeschrijvingBehandeling() {
return "Haren worden geknipt";
}
}
-----------------------------------------------------
public class Wassen {
private double prijs;
private String beschrijving;
public Wassen() {
this.prijs = 7.50;
this.beschrijving = " en haren worden gewassen";
}
public double getPrijsBehandeling() {
return prijs;
}
public String getBeschrijvingBehandeling() {
return beschrijving;
}
}

The methods (aka “operation”, in UML speak) geefPrijs()and geefBeschrijving() are indeed designed according to the template method pattern: the base class implements the general algorithm, encapsulating the “primitive” parts that may need to be specialized into separate methods that can be overridden (i.e. “specialized”, in UML speak) by class extensions.
If the base class cannot provide its own implementation of a “partial” methods, you would make it abstract. But although this is how the pattern is usually described, in practice this is not an obligation: it is perfectly valid that the base class provides a default behavior that is not always overridden. The UML diagram should reflect your design in this regard, if there are abstract elements.
Some additional hints
In your design getPrijs() (template method) and getPrijsBehandeling() (primitive used in the template method) are both public and have names that create a risk of confusion:
if the primitive is not intended to be used for other purposes, it is one of the rare situation where making it protected could be a good idea.
if you prefer to avoid protected, you could use a naming convention. GoF suggests the “do” prefix inspired from a framework that didn’t survive. I prefer “prepare” like preparePrijsBehandeling() and prepareBeschrijvingBheandeling() because it immediately raises the question “prepare for what?” preventing inappropriate use.
It’s not the case here, but of course, if the primitive is a primitive operation that makes sense outside of the template methods, then there is no issue (example: surface() or perimeter() or barycenter() that are geometric characteristics of a shape that may be relevant for some template methods but make sense on their own).

Related

Override Setter in Subclass

I'm stuck with a problem here. I want to change the setter from a attribute from the superclass (parent class) in my subclass (child) however when I overide this method in my subclass I can't access my private attributes from the supperclass. And the point is, they have to stay private.
Superclass (problem: setMinimumVoorraad(int voorraad);)
package domein;
public abstract class Artikel implements Weegbaar
{
private String omschrijving;
private double prijs;
private int aantalInStock;
private int minimumVoorraad;
public Artikel(String omschrijving, double prijs, int aantalInStock, int minimumVoorraad)
{
this.setOmschrijving(omschrijving);
this.setPrijs(prijs);
this.setAantalInStock(aantalInStock);
this.setMinimumVoorraad(minimumVoorraad);
}
#Override
public String toString()
{
String output = String.format(" \n omschrijving: %s \n prijs: %f \n In stock %d (minimumvoorraad = %d) \n", this.omschrijving, this.prijs, this.aantalInStock, this.minimumVoorraad);
return output;
}
//----Getters----
public String getOmschrijving() {
return omschrijving;
}
public double getPrijs() {
return prijs;
}
public int getAantalInStock() {
return aantalInStock;
}
public int getMinimumVoorraad() {
return minimumVoorraad;
}
//----Setters----
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
public void setPrijs(double prijs) {
this.prijs = prijs;
}
public void setAantalInStock(int aantalInStock) {
this.aantalInStock = aantalInStock;
}
public void setMinimumVoorraad(int minimumVoorraad)
{
if(minimumVoorraad < 2)
this.minimumVoorraad = 3;
else
this.minimumVoorraad = minimumVoorraad;
}
}
Subclass
package domein;
public class Food extends Artikel
{
private String houdbaarheidsDatum;
private double nettoGewicht;
public Food(String omschrijving, double prijs, int aantalInStock, int minimumVoorraad, String houdbaarheidsDatum, double nettoGewicht)
{
super(omschrijving, prijs, aantalInStock, minimumVoorraad);
this.setHoudbaarheidsDatum(houdbaarheidsDatum);
this.setNettoGewicht(nettoGewicht);
}
#Override
public boolean isWeegbaar()
{
return true;
}
//----Getters----
public String getHoudbaarheidsDatum() {
return houdbaarheidsDatum;
}
public double getNettoGewicht() {
return nettoGewicht;
}
//----Setters----
public void setHoudbaarheidsDatum(String houdbaarheidsDatum) {
this.houdbaarheidsDatum = houdbaarheidsDatum;
}
public void setNettoGewicht(double nettoGewicht) {
this.nettoGewicht = nettoGewicht;
}
#Override
public void setMinimumVoorraad(int minimumVoorraad)
{
if(minimumVoorraad < 5)
this.minimumVoorraad = 6;
else
this.minimumVoorraad = minimumVoorraad;
}
}
Someone who can help me?
Thanks in advance.
One possibility is to implement the subclass's setter in terms of the superclass's setter (which, presumably, you do have access to).
For example, assuming the setter is setFoo, then the subclass's version might be:
public void setFoo(Foo f) {
// Do subclass stuff pre-setting, if any
super.setFoo(f);
// Do subclass stuff post-setting, if any
}
The answer given above by NPE is absolutely the best way to go about solving this problem. It is elegant and honors basic inheritance contracts between superclass and subclass. Even in your original post, the subclass is actually more restrictive than the superclass, so doing something like:
#Override
public void setMinimumVoorraad(int minimumVoorraad)
{
if(minimumVoorraad <= 5)
super.setMinimumVoorraad(6);
else
super.setMinimumVoorraad(minimumVoorraad);
}
exactly as NPE suggested would probably work. (Note how I modified your if test. Not sure if it's a typo, but in the original implementation 5 would be a valid minimum, but input like 4 would set it to 6.)
Other (possibly acceptable) patterns would be to:
Make the members in your Parent class protected, which would give visibility. (Realize that you did mention a private restriction; this pattern is solely mentioned to provide a more complete overall answer.)
Delegate the validation logic to another method (that is non-private). This way the child can override the validation method.
And now on to the (probably unacceptable) pattern of using Java reflection:
#Override
public void setMinimumVoorraad(int minimumVoorraad) {
try {
Field field = this.getClass().getSuperclass().getDeclaredField("minimumVoorraad");
field.setAccessible(true);
if(minimumVoorraad <= 5)
field.set(this, 6);
else
field.set(this, minimumVoorraad);
field.setAccessible(false);
}
catch(NoSuchFieldException | IllegalAccessException e) {
// do something
}
}
It's worth noting that if you never ever do this in your entire life you will probably be the better for it. Not only does it completely break all contracts, but it relies on hard-coded Strings to do field name lookups, which in and of itself is pretty painful. But it does exist. And no good answer (already given above by NPE) would be complete without an example of how not to do something...

List of enum vs. class of booleans

For now, I have a class with fields.
#Entity
public class Fuel {
#Id #GeneratedValue
private Long id;
private boolean diesel;
private boolean gasoline;
private boolean etanhol;
private boolean cng;
private boolean electric;
public Fuel() {
// this form used by Hibernate
}
public List<String> getDeclaredFields() {
List<String> fieldList = new ArrayList<String>();
for(Field field : Fuel.class.getDeclaredFields()){
if(!field.getName().contains("_") && !field.getName().equals("id") && !field.getName().equals("serialVersionUID") ) {
fieldList.add(field.getName());
}
Collections.sort(fieldList);
}
return fieldList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isDiesel() {
return diesel;
}
public void setDiesel(boolean diesel) {
this.diesel = diesel;
}
public boolean isGasoline() {
return gasoline;
}
public void setGasoline(boolean gasoline) {
this.gasoline = gasoline;
}
public boolean isEtanhol() {
return etanhol;
}
public void setEtanhol(boolean etanhol) {
this.etanhol = etanhol;
}
public boolean isCng() {
return cng;
}
public void setCng(boolean cng) {
this.cng = cng;
}
public boolean isElectric() {
return electric;
}
public void setElectric(boolean electric) {
this.electric = electric;
}
}
I think it makes sense, but when I asked another question (maybe a stupid example since there can only be either automatic or manual gearbox) https://stackoverflow.com/questions/11747644/selectonemenu-from-declared-fields-list-in-pojo , a user recommend me to use enums instead. Like this way:
public enum Fuel {
DIESEL("diesel"),
GASOLINE("gasoline"),
ETANHOL("etanhol"),
CNG("cng"),
ELECTRIC("electric");
private String label;
private Fuel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
However, since there exists hybrids on the market (like Toyota Prius) the parent class would implement the boolean class at this way:
private Fuel fuel = new Fuel();
and if using enumerated list at this way:
private List<Fuel> fuelList = new ArrayList<Fuel>();
What is the best practice? Keep in mind that I might have 100 different fuels (just for example =). Do not forget that it is an entity and hence persisted in a database.
Thanks in advance =)
It sounds to me like you want an EnumSet, yes, definitely over a bunch of bool's.
This reminds me a lot of the design patterns for flags and I recently posted an SO question on exactly that: Proper design pattern for passing flags to an object
This supports having 100 different fuel types easily. However it doesn't support a car using 100 different fuel types simultaneously easily. But that to me sounds perfectly fine - it would be very hard to build such a car and this is perfectly reflected in the programmatic complexity of coding this :) (Unless of course it really was just supporting all corn-based fuels - in which you might prefer a polymorphic pattern.)
You should definetly use enums.
Image you want to get the fuel-type of an object.
If you would use bools you would end up with something like this:
if (myClass.IsGasoline())
else if (myClass.IsOtherFuel())
else if
...
If you use enums you can simply do something like:
Fuel fuel = myClass.GetFuelType()
(This is just pseudo-code ;))
If the number of hybrids is low, and I guess it will be better to use Enums, and include hybrids as a different case.
Otherwise you will have to manage the logic in a way that can be cumbersome, as when you set a certain Fuel to true you, most likely, will have also to set to false the current one set to true. I am saying this as you have setters for your fuel categories and you don't only define at construction.
EDIT: the way on how to ask for the type of fuel you are using would also be an argument in favor of enums.

Implementation question regarding base classes and derived classes

I have a question regarding the best way to implement this. I'm going to describe my current implementation and how I seem to have painted myself into a corner:
I have an abstract class called Package:
public abstract class Package {
protected String description;
protected String packagingCode;
protected Dimension dimensions;
protected Weight weight;
protected Package() {
this.description = null;
this.packagingCode = null;
this.dimensions = null;
this.weight = null;
}
protected Package(String description, String packagingCode, Dimension dimensions, Weight weight) throws ShippingException {
this.description = description;
this.packagingCode = packagingCode;
this.dimensions = dimensions;
this.weight = weight;
String exceptionMessage = "";
if(!meetsWeightRequirements()) {
exceptionMessage = "This package's weight exceeds limits. ";
}
if(!meetsDimensionalRequirements()) {
exceptionMessage += "This package's dimensions exceed limits.";
}
if(!StringUtils.isEmpty(exceptionMessage)) {
throw new ShippingException(exceptionMessage);
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPackagingCode() {
return packagingCode;
}
public void setPackagingCode(String packagingCode) {
this.packagingCode = packagingCode;
}
public Dimension getPackageDimensions() {
return dimensions;
}
public void setPackageDimensions(Dimension dimensions) throws ShippingException {
this.dimensions = dimensions;
if(!meetsDimensionalRequirements()) {
this.dimensions = null;
throw new ShippingException("This package's dimensions exceed limits.");
}
}
public Weight getPackageWeight() {
return weight;
}
public void setPackageWeight(Weight weight) throws ShippingException {
this.weight = weight;
if(!meetsWeightRequirements()) {
this.weight = null;
throw new ShippingException("This package's weight exceeds limits.");
}
}
public abstract boolean meetsWeightRequirements();
public abstract boolean meetsDimensionalRequirements();
}
Then I have classes that extend this abstract class like so:
public class WeightBasedPackage extends Package {
public boolean meetsWeightRequirements() {
Weight weight = this.getPackageWeight();
boolean meetsRequirements = false;
if(weight != null) {
meetsRequirements = (weight.getWeight() > 0);
}
return meetsRequirements;
}
public boolean meetsDimensionalRequirements() {
return true;
}
}
I have another object (ShipRequest) that maintains a List of Packages (List<Package>). I also have a services (eg WeightBasedPackageShipService) that uses this object and can access this list of packages. This implementation has worked fine because the services don't really care what type of package it is. The only difference between the packages is the way they implement the abstract methods.
Now here is where the problem comes in. I created a new class:
public class OrderQuantityPackage extends Package {
int quantity;
public OrderQuantityPackage() {
super();
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return this.quantity;
}
public boolean meetsWeightRequirements() {
return true;
}
public boolean meetsDimensionalRequirements() {
return true;
}
}
Which has a quantity field. I need to access this field in the service (OrderQuantityPackageShipService). However, since it is of type Package I have to cast it (it seems kinda kludgey).
My question is, how do I implement this in a better fashion (so I don't have to cast) and also ensure type-safety (So that if you are using OrderQuantityPackageShipService, the package must be of type OrderQuantityPackage). I thought about using Generics, but it seems a little to kludgey for what I am trying to do (ShipRequest has a bunch of other attributes and it seemed strange to genericize it based on the type of package).
Thanks.
public abstract class Package {
protected String description; // These shouldn't be private fields instead of protected?
protected String packagingCode; // Nah, I don't think so, otherwise how could I store a value into the Quantity field? =P
protected Dimension dimensions;
protected Weight weight;
protected int quantity;
// Constructors, getters and setters...
public virtual int getQuantity {
throw new NotImplementedException();
}
public virtual int setQuantity(int quantity) {
throw new NotImplementedException();
}
}
public final class OrderQuantityPackage extends Package {
public override int getQuantity {
return super.quantity;
}
public override void setQuantity(int quantity) {
super.quantity = quantity;
}
}
I'm not completely sure about the syntax though, and neither about the NotImplementedException, but I hope you get the idea. So, any Package derived class that needs or require a quantity may do so by overriding the getter and setter of the Quantity property.
No exception should be thrown as of where the Quantity won't be required, it shouldn't get called, so no exception shall be thrown. Furthermore, it testifies that your model only does what it is required when times come.
In addition to it, OrderQuantityShipService shouldn't require a Weight property within the OrderQuantityPackage, and as written by Vivin, one could access the weight anyway.
Otherwise, a simple cast within your service should do it. It is no dirty way to go to use casting. For instance, one must cast the sender object within an event handler to the proper control type he wishes to check for name, state or other property values! The most general class is then passed on to the event, and one must cast... And this, that is not me who said to opt this way, these are software engineers!...
EDIT Vivin, how do one cast from a data type to another in JAVA, is it as in C/C++/C# ?
CastedType variable = (CastedType)TypeCast;
Short Answer: Dependency Inversion
You have a OrderQuantityPackageShipService class that requires certain features from the objects that it processes. So OrderQuantityPackageShipService should be the one specifying those requirements. Typically this is done with an interface. If it is very specific to the service, create the interface nested. ie:
class OrderQuantityPackageShipService {
//...
interface QuantityPackage {
int getQuantity();
// ...
}
}
if it can be used in a consistent manner by other services, define it outside of the OrderQuantityPackageShipService class.
Then have certain packages implement that interface...
Maybe you should create an abstract service and extend it for the different kinds of packages to handle. You could have the handling method be abstract and have each kind of service know what to do with the corresponding package. If you're not to mix types of packages then this might work.
One thing I can think of is why would you need to access the quantity attribute in the class OrderQuantityPackageShipService ? As I look at it you have a getter and setter for each attribute of the class Package. Are these getters and setters really needed ? Having getters/setters for all those attributes doesn't go well with encapsulation.
Can you think of providing public methods in Package class that operate at a higher level and don't expose the internal attributes ? Wouldn't that help ?

Alternative to enum in Java 1.4

Since Java 1.4 doesn't have enums I'm am doing something like this:
public class SomeClass {
public static int SOME_VALUE_1 = 0;
public static int SOME_VALUE_2 = 1;
public static int SOME_VALUE_3 = 2;
public void receiveSomeValue(int someValue) {
// do something
}
}
The caller of receiveSomeValue should pass one those 3 values but he can pass any other int.
If it were an enum the caller could only pass one valid value.
Should receiveSomeValue throw an InvalidValueException?
What are good alternatives to Java 5 enums?
Best to use in pre 1.5 is the Typesafe Enum Pattern best described in the book Effective Java by Josh Bloch. However it has some limitations, especially when you are dealing with different classloaders, serialization and so on.
You can also have a look at the Apache Commons Lang project and espacially the enum class, like John has written. It is an implementation of this pattern and supports building your own enums.
I'd typically create what I call a constant class, some thing like this:
public class MyConstant
{
public static final MyConstant SOME_VALUE = new MyConstant(1);
public static final MyConstant SOME_OTHER_VALUE = new MyConstant(2);
...
private final int id;
private MyConstant(int id)
{
this.id = id;
}
public boolean equal(Object object)
{
...
}
public int hashCode()
{
...
}
}
where equals and hashCode are using the id.
Apache Commons Lang has an Enum class that works well and pretty well covers what Java 5 Enums offer.
If the application code base is going to use lot of enums, then I would prefer following solution, which I have used in my application.
Base Class
public class Enum {
protected int _enumValue;
protected Enum(int enumValue) {
this._enumValue = enumValue;
}
public int Value() {
return this._enumValue;
}
}
Your enumerations will then follow these pattern
Actual Enum
public class DATE_FORMAT extends Enum {
public static final int DDMMYYYY = 1;
public static final int MMDDYYYY = 2;
public static final int YYYYMMDD = 3;
public DATE_FORMAT(int enumValue) {
super(enumValue);
}
}
And your code can consume this enum as follows
String getFormattedDate(DATE_FORMAT format) {
String sDateFormatted = "";
switch (format.Value()) {
case DATE_FORMAT.DDMMYYYY :
break;
case DATE_FORMAT.MMDDYYYY :
break;
case DATE_FORMAT.YYYYMMDD :
break;
default:
break;
}
return sDateFormatted;
}
Caller can use the function as
void callerAPI() {
DATE_FORMAT format = new DATE_FORMAT(DATE_FORMAT.DDMMYYYY);
String sFormattedDate = getFormattedDate(format);
}
This is yet not full proof against intitializing derived Enum objects with any integer value. However it can provide good syntactic guideline to work in non-enum environment.

what is the difference between using the visitor pattern and an interface?

What is the difference between applying the visitor design pattern to your code and the following approach:
interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s) {
this.s = s;
}
public void setInterface(Dointerface d) {
this.d = d;
}
public void perform() {
d.perform(this);
}
public static void main(String[] args) {
T t = new T("Geonline");
t.setInterface(new Dointerface() {
public void perform(Object o) {
T a = (T)o;
System.out.println(a.getS());
}
});
t.perform();
}
}
I assume that by using interfaces, we're not really separating the algorithm.
There is quite a big difference.
The visitor pattern uses interfaces, but its purpose is to be able to perform an operation to one or more classes (who implement an interface) without having to change the classes. Hence, the implementation actually "visits" the class and does its thing without the class being modified.
An interface is a basic concept used to provide a common API to a potentially diverse group of classes. The typical test for an interface is that classes that share it are alike in at least that one respect (is-like-a) and in those cases can be treated as such.
Here is a simple example on wikipedia that shows a couple of visitors in java.
Two things:
In your example you need two methods. The perfom and the setInterface. With a visitor pattern you would only need one method, the perfom, usually called accept.
If you need more than one 'performer', you will have to set the performer -via the setInterface method- for each. This makes it impossible to make your class immutable.
The most important difference in these examples is that in the visitor case you retain the compile-time concrete type of "this". This allows you to use double dispatch, where the method to be called is dependent on both the concrete data type and the visitor implementation. Double dispatch is just a special case of multiple dispatch where the method invoked is dependent on the receiver and the types of the parameters to the method. Java is of course single dispatch but some other languages support multiple dispatch.
The basic driving force behind the visitor pattern is that by using interfaces on the concrete nodes, every operation that needs to be added to a composite data structure must change every node. The visitor pattern uses a generic (static) pattern on the nodes so that dynamically adding operations is easy. The downside is that modifying the data structure (by adding or removing concrete nodes) becomes more difficult as all operation visitors are affected.
In general, this trade=off is a better match as it's more frequent to extend operations over a data structure than to change the data structure itself. Here's a lengthier writing of mine on how to use visitors and a bunch of considerations:
http://tech.puredanger.com/2007/07/16/visitor/
You might fairly ask if there is a pattern that allows us to do both: add operations or extend our data structures without breaking existing code. This is known as The Expression Problem as coined by Philip Wadler. You can find some links on this and more here:
http://tech.puredanger.com/presentations/design-patterns-reconsidered
A Visitor pattern is used when you have a data structure made up of many different classes and you have multiple algorithms that require a different operation for each class. In your example your DoInterface implementation only does one operation on one type. The only thing you do is print the result of getS() and because you cast o to T you can only do this to classes of type T.
If you wanted to apply your interface to a typical visitor style class you your the class with your DoInterface.perform function would likely end up with a big if else if statement in it something like this:
public void visit(Object o) {
if (o instanceof File)
visitFile((File)o);
else if (o instanceof Directory)
visitDirectory((Directory)o);
else if (o instanceof X)
// ...
}
Because this uses Object it will allow callers with any type which can create errors which will only show up at runtime. A Visitor gets around this by creating a “visitType” function for each type in the data structure. The classes in the data structure are then responsible for knowing which function on the visitor to call. The mapping is performed by each of the data structure’s classes implementing an accept function that then calls back on the Visitor class. If the function for the type does not exist on the visitor you get a compile error. The accept method looks like this:
#Override
public void accept(FileSystemVisitor v) {
v.visitFile(this);
}
Part of the trouble with the Visitor pattern is that it takes quite a lot of code to really do it justice in a sample. I think this is why a lot of people don't get it as it is easy to get distracted by the other code. I have created a simple file system sample that hopefully shows how to use a visitor more clearly. It creates a composite with some files and directories in and then performs two operations on the hierarchy. In practice you would probably want more than two data classes and two operations to justify this pattern but this is only an example.
public class VisitorSample {
//
public abstract class FileSystemItem {
public abstract String getName();
public abstract int getSize();
public abstract void accept(FileSystemVisitor v);
}
//
public abstract class FileSystemItemContainer extends FileSystemItem {
protected java.util.ArrayList<FileSystemItem> _list = new java.util.ArrayList<FileSystemItem>();
//
public void addItem(FileSystemItem item)
{
_list.add(item);
}
//
public FileSystemItem getItem(int i)
{
return _list.get(i);
}
//
public int getCount() {
return _list.size();
}
//
public abstract void accept(FileSystemVisitor v);
public abstract String getName();
public abstract int getSize();
}
//
public class File extends FileSystemItem {
//
public String _name;
public int _size;
//
public File(String name, int size) {
_name = name;
_size = size;
}
//
#Override
public void accept(FileSystemVisitor v) {
v.visitFile(this);
}
//
#Override
public String getName() {
return _name;
}
//
#Override
public int getSize() {
return _size;
}
}
//
public class Directory extends FileSystemItemContainer {
//
private String _name;
//
public Directory(String name) {
_name = name;
}
//
#Override
public void accept(FileSystemVisitor v) {
v.visitDirectory(this);
}
//
#Override
public String getName() {
return _name;
}
//
#Override
public int getSize() {
int size = 0;
for (int i = 0; i < _list.size(); i++)
{
size += _list.get(i).getSize();
}
return size;
}
}
//
public abstract class FileSystemVisitor {
//
public void visitFile(File f) { }
public void visitDirectory(Directory d) { }
//
public void vistChildren(FileSystemItemContainer c) {
for (int i = 0; i < c.getCount(); i++)
{
c.getItem(i).accept(this);
}
}
}
//
public class ListingVisitor extends FileSystemVisitor {
//
private int _indent = 0;
//
#Override
public void visitFile(File f) {
for (int i = 0; i < _indent; i++)
System.out.print(" ");
System.out.print("~");
System.out.print(f.getName());
System.out.print(":");
System.out.println(f.getSize());
}
//
#Override
public void visitDirectory(Directory d) {
for (int i = 0; i < _indent; i++)
System.out.print(" ");
System.out.print("\\");
System.out.print(d.getName());
System.out.println("\\");
//
_indent += 3;
vistChildren(d);
_indent -= 3;
}
}
//
public class XmlVisitor extends FileSystemVisitor {
//
private int _indent = 0;
//
#Override
public void visitFile(File f) {
for (int i = 0; i < _indent; i++)
System.out.print(" ");
System.out.print("<file name=\"");
System.out.print(f.getName());
System.out.print("\" size=\"");
System.out.print(f.getSize());
System.out.println("\" />");
}
//
#Override
public void visitDirectory(Directory d) {
for (int i = 0; i < _indent; i++)
System.out.print(" ");
System.out.print("<directory name=\"");
System.out.print(d.getName());
System.out.print("\" size=\"");
System.out.print(d.getSize());
System.out.println("\">");
//
_indent += 4;
vistChildren(d);
_indent -= 4;
//
for (int i = 0; i < _indent; i++)
System.out.print(" ");
System.out.println("</directory>");
}
}
//
public static void main(String[] args) {
VisitorSample s = new VisitorSample();
//
Directory root = s.new Directory("root");
root.addItem(s.new File("FileA", 163));
root.addItem(s.new File("FileB", 760));
Directory sub = s.new Directory("sub");
root.addItem(sub);
sub.addItem(s.new File("FileC", 401));
sub.addItem(s.new File("FileD", 543));
Directory subB = s.new Directory("subB");
root.addItem(subB);
subB.addItem(s.new File("FileE", 928));
subB.addItem(s.new File("FileF", 238));
//
XmlVisitor xmlVisitor = s.new XmlVisitor();
root.accept(xmlVisitor);
//
ListingVisitor listing = s.new ListingVisitor();
root.accept(listing);
}
}
The only thing that I see that is readily obvious is that by storing the interface, you make it so you have to do two operations rather than one to invoke it. I suppose that this could make sense if you are repeatedly going to perform the same action once the interface is set, but I think you could stick with the standard Visitor and accomplish the same thing.

Categories