How to handle interacting decorators - oop

Given the classic coffee decorator example (copied from Wikipedia).
public interface Coffee {
public double getCost();
}
public class SimpleCoffee implements Coffee {
public double getCost() {
return 1;
}
}
public abstract class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
public CoffeeDecorator(Coffee c) {
this.decoratedCoffee = c;
}
public double getCost() {
return decoratedCoffee.getCost();
}
}
class WithMilk extends CoffeeDecorator {
public WithMilk(Coffee c) {
super(c);
}
public double getCost() {
return super.getCost() + MILKCOST;
}
public int someAttribute;
}
class WithMocha extends CoffeeDecorator {
public WithMocha(Coffee c) {
super(c);
}
public double getCost() {
return super.getCost() + MOCHACOST;
}
}
Suppose I want my WithMocha cost to use someAttribute if the WithMilk decorator exists, how would one design such a decorator system?
Is the decorator pattern even the best approach?

No it isn't, as casting the coffee instance to a decorator would violate Liskovs substution principle.
As your question do not detail the real problem that you want to solve it's hard to give a proper answer.
If you want to construct objects where the different parts can interact the Builder pattern is a much better alternative.

Related

Is it ok to override a virtual method but provide no implementation?

I'm trying to create a class heirachy for a game, there is an Item class which is the base class for all items in the game. The problem is that some derived items (like potion) might not implement some of the abstract methods defined by the item.
Is it ok for derived classes to implement an abstract method with "do nothing"?
Example: https://dotnetfiddle.net/jJABN1
using System;
using System.Collections.Generic;
public abstract class Item
{
public abstract void Use();
}
public class Potion : Item
{
public override void Use()
{
// do nothing
return;
}
}
public class Sword : Item
{
public override void Use()
{
Console.WriteLine("Sword used!");
return;
}
}
public class Program
{
public static void Main()
{
List<Item> items = new List<Item>();
Item potion = new Potion();
Item sword = new Sword();
items.Add(potion);
items.Add(sword);
for (int i = 0; i < items.Count; i++)
{
Item item = items[i];
item.Use();
}
}
}
One of Robert Martin's SOLID Principles - Interface Segregation Principle addresses this situation. It basically says that a client should not be exposed to methods it doesn't need.
An example of violating the Interface Segregation Principle:
// Abstraction
public abstract class Printer
{
public abstract void Print();
public abstract void Scan();
}
// Implementations
public class SomeAllInOnePrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
Console.WriteLine("Scanning...");
}
}
public class SomeBasicPrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
// Basic printers can't scan
}
}
This is usually solved by separating an abstract class to multiple smaller abstract classes that can optionally inherit one other:
// Abstractions
public abstract class Printer
{
public abstract void Print();
}
public abstract class AllInOnePrinter : Printer
{
public abstract void Scan();
}
// Implementations
public class SomeAllInOnePrinter : AllInOnePrinter
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
Console.WriteLine("Scanning...");
}
}
public class SomeBasicPrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
}
Technically, there could be an edge-case (should be uncommon!) where a deriving class doesn't need to implement all the methods, in such a case I'd rather it to override and throw an error to signal the user that this method should not be used.
That said, in the provided example there is only one method, so the question is: if a derived class doesn't need this method - why do you need to inherit the abstract class to begin with? if it's just in order to provide an example that's understandable - but better improve the example to include other methods that are used in the derived class.

Is there a better OOP approach to nesting strategy patterns?

Is there a better OOP approach to nesting strategy patterns?
I have a Genetic Algorithm that I want to be able to choose a Fitness Algorithm and Fitness Functions independently at runtime. The Fitness Algorithm will use the Fitness Function through Composition. Currently, I am using the Strategy Pattern with a Factory method (SPFM) to choose the algorithm used and then using another SPFM for choosing the Fitness Functions used by the algorithm.
Fitness Algorithm SPFM
public interface I_Fitness {
//Accessors
public Population orderByFitness(Population population);
}
public class FitnessFactory {
public static I_Fitness fitnessAlgorithmFactory(String fitnessType){
if(fitnessType.equalsIgnoreCase("cumulative")){return new FitnessCumulative();}
if(fitnessType.equalsIgnoreCase("weighted")){return new FitnessWeighted();}
return null;
}
}
public class FitnessCumulative implements I_Fitness {
#Override
public Population orderByFitness(Population population) {
I_FitnessFunctions fitnessFunctions = fitnessFunctionFactory(fitnessFunctionType);
...
}
}
public class FitnessWeighted implements I_Fitness {
#Override
public Population orderByFitness(Population population) {
I_FitnessFunctions fitnessFunctions = fitnessFunctionFactory(fitnessFunctionType);
...
}
}
Fitness Function SPFM
public interface I_FitnessFunctions {
//Accessors
public Double[] getFitness(Chromosome chromosome);
}
public class FitnessFunctionsFactory {
public static I_FitnessFunctions fitnessFunctionsFactory(String fitnessFunctionType){
if(fitnessFunctionType.equalsIgnoreCase("FitnessFunctions1")){return new fitnessFunctions1();}
if(fitnessFunctionType.equalsIgnoreCase("FitnessFunctions2")){return new fitnessFunctions2();}
return null;
}
}
public class fitnessFunctions1 implements I_FitnessFunctions {
#Override
public Double getFitness(Chromosome chromosome) {
...
}
}
public class fitnessFunctions2 implements I_FitnessFunctions {
#Override
public Double getFitness(Chromosome chromosome) {
...
}
}

Where to put common members variables in decorators

Given the classic coffee decorator example (copied from Wikipedia).
public interface Coffee {
public double getCost();
}
public class SimpleCoffee implements Coffee {
public double getCost() {
return 1;
}
}
public abstract class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
public CoffeeDecorator(Coffee c) {
this.decoratedCoffee = c;
}
public double getCost() {
return decoratedCoffee.getCost();
}
}
class WithMilk extends CoffeeDecorator {
public WithMilk(Coffee c) {
super(c);
}
public double getCost() {
return super.getCost() + 0.5;
}
}
Let's say now the price of all decorators (e.g. Milk) depends on some attribute that all coffees will have (say the size of the coffee) and that the size of coffee is NEVER used elsewhere. Where should add coffee size to the class hierarchy?
I can put it in the Coffee Interface
public interface Coffee {
public double getCost(); // Returns the cost of the coffee
public/protected double size;
}
If it's set to public, the size is unnecessarily exposed
If it's set to protected, decorators can't really access it through decoratedCoffee (see this post Java: cannot access a protected member of the superclass in the extending subclass and Why can't a derived class call protected member function in this code?)
I can put it in CoffeeDecorator, but then I would have to modify the constructor to
public CoffeeDecorator(Coffee c) {
if c is of type CoffeeDecorator
size = c.size;
this.decoratedCoffee = c;
}
Which somehow doesn't seem like the most elegant solution... (Obviously digging through the chain of decoratedCoffees until I find one with non-null size is not an option either)
I can put it in each decorator which just goes against the design principles.
I'm pretty sure this scenario comes up quite often, I'd like to know what is the best way of handling such case?
Thanks in advance.
--- Edit 31/3/2016 ---
Clarify that the certain attribute (previously cup size, now renamed to coffee size) is something that all coffees should have.
I don't think that adding the Cup size into any of these classes is a good idea.
It just doesn't fit in there, because the coffee knows nothing about cups.
The Cup can be a separate class (theat code as pseudo-code, I am not very familiar with java syntax):
public class Cup {
private Coffee coffee;
public Cup(Coffee c) {
this.coffee = c;
}
public getCost() {
return this.getSize() * c.getCost();
}
public getSize() {
return 1; // standard cup
}
}
public class BigCup extends Cup {
public getSize() {
return 2; // double size
}
}
So now you can do new BigCup(new WithMilk(new Coffee())).
Alternatively the Cup can also be a decorator, it makes sense in terms of programming, but maybe a bit less sense in terms of real life (because now the Cup also implements Coffee, sounds fun):
public class Cup extends CoffeeDecorator {
public Cup(Coffee c) {
super(c);
}
public getCost() {
return this.getSize() * super.getCost();
}
public getSize() {
return 1; // standard cup
}
}
public class BigCup extends Cup {
public getSize() {
return 2; // double size
}
}

use 2 class by only calling a single class

class merged(){
//i want to be able to use class sample1 and sample2 by just calling this merged class
}
class sample1(){}
class sample2(){}
Or doing this isnt ideal? can you please suggest how can I implement this more efficiently?
Composition?
Class merged(){
sample1 s1 = new sample1();
sample1 s2 = new sample2();
void doSomething1()
{
s1.dosomething();
}
void doSomething2()
{
s2.dosomething();
}
}
You can go one of the ways (or a mixture of a couple of ways) as shown below (Note: Java convention is to have the first letter of class names capital):
public interface Sample1() {
// abstract methods
}
public class Sample2() {
// whatever
}
public class Merged() extends Sample2 implements Sample1 {
// whatever
}
OR
public class Sample1() {
// abstract methods
}
public class Sample2() {
// whatever
}
public class Merged() {
Sample1 ob = new Sample1();
Sample2 ob2 = new Sample2();
}
OR
public interface Sample1() {
// abstract methods
}
public abstract Sample2() {
// abstract and other methods
}
public class Merged() extends Sample2 implements Sample1 {
// whatever
}
OR
public interface Sample1() {
// abstract methods
}
public interface Sample2() {
// abstract methods
}
public class Merged() implements Sample1, Sample1 {
// whatever
}
You should do this with interfaces. Modern Object-Oriented programming languages don't support multiple inheritance (believe me, it's a good thing that they don't) so you need to fix this by using interfaces.
Here's an example in Java:
public interface GasolineUser {
public double getGasolineGallonsLeft();
}
public interface MusicPlayer {
public void playMusic();
}
public class Car implements GasolineUser, MusicPlayer {
public double getGasolineGallonsLeft(){
// return gallons left
}
public void playMusic(){
// play music
}
}
Note that Car in this case is both a GasolineUser AND a MusicPlayer, so it can be passed to any method that requires one or any method that requires the other. Similar inheritance exists in C#. For more information on the usefulness of interfaces, do a google search on OOP Interfaces.

Adding State in Decorator Pattern

I wonder how to add state to the chain of decorators that will be available to the consumer. Given this simplified model:
abstract class AbstractPizza
{
public abstract print(...);
}
class Pizza : AbstractPizza
{
public int Size { get; set; }
public print(...);
}
abstract class AbstractPizzaDecorator
{
public Pizza:AbstractPizza;
public abstract print();
}
class HotPizzaDecorator : AbstractPizzaDecorator
{
public int Hotness { get; set; }
public print(...);
}
class CheesyPizzaDecorator : AbstractPizzaDecorator
{
public string Cheese { get; set; }
public print(...);
}
void Main()
{
BigPizza = new Pizza();
BigPizza.Size = 36;
HotBigPizza = new HotPizzaDecorator();
HotBigPizza.Pizza = BigPizza;
HotBigPizza.Hotness = 3;
HotBigCheesyPizza = new CheesyPizzaDecorator();
HotBigCheesyPizza.Pizza = HotBigPizza;
HotBigCheesyPizza.Cheese = "Blue";
HotBigCheesyPizza.print();
HotBigCheesyPizza.size = 28; // ERRRRRR !
}
Now if they all implement the print method and propagate that though the chain, it's all good. But how does that work for the state? I can't access the size property on the HotBigCheesyPizza.
What's the part that I'm missing? Wrong pattern?
Thanks for helping!
Cheers
The decorator pattern is for adding additional behavior to the decorated class without the client needing to adjust. Thus it is not intended for adding a new interface (e.g. hotness, cheese) to the thing being decorated.
A somewhat bad example of what it might be used for is where you want to change how size is calculated: you could create a MetricSizePizzaDecorator that converts the size to/from English/metric units. The client would not know the pizza has been decorated - it just calls getSize() and does whatever it needs to do with the result (for example, to calculate the price).
I would probably not use the decorator in my example, but the point is: it does not alter the interface. In fact, nearly all design patterns come down to that - adding variability to a design without changing interfaces.
one way of adding state is by using a self referential data structure (a list). but this uses the visitor pattern and does more than you probably want. this code is rewritten from A little Java, a few patterns
// a self referential data structure with different types of nodes
abstract class Pie
{
abstract Object accept(PieVisitor ask);
}
class Bottom extends Pie
{
Object accept(PieVisitor ask) { return ask.forBottom(this); }
public String toString() { return "crust"; }
}
class Topping extends Pie
{
Object topping;
Pie rest;
Topping(Object topping,Pie rest) { this.topping=topping; this.rest=rest; }
Object accept(PieVisitor ask) { return ask.forTopping(this); }
public String toString() { return topping+" "+rest.toString(); }
}
//a class to manage the data structure
interface PieManager
{
int addTopping(Object t);
int removeTopping(Object t);
int substituteTopping(Object n,Object o);
int occursTopping(Object o);
}
class APieManager implements PieManager
{
Pie p=new Bottom();
// note: any object that implements a rational version of equal() will work
public int addTopping(Object t)
{
p=new Topping(t,p);
return occursTopping(t);
}
public int removeTopping(Object t)
{
p=(Pie)p.accept(new RemoveVisitor(t));
return occursTopping(t);
}
public int substituteTopping(Object n,Object o)
{
p=(Pie)p.accept(new SubstituteVisitor(n,o));
return occursTopping(n);
}
public int occursTopping(Object o)
{
return ((Integer)p.accept(new OccursVisitor(o))).intValue();
}
public String toString() { return p.toString(); }
}
//these are the visitors
interface PieVisitor
{
Object forBottom(Bottom that);
Object forTopping(Topping that);
}
class OccursVisitor implements PieVisitor
{
Object a;
OccursVisitor(Object a) { this.a=a; }
public Object forBottom(Bottom that) { return new Integer(0); }
public Object forTopping(Topping that)
{
if(that.topping.equals(a))
return new Integer(((Integer)(that.rest.accept(this))).intValue()+1);
else return that.rest.accept(this);
}
}
class SubstituteVisitor implements PieVisitor
{
Object n,o;
SubstituteVisitor(Object n,Object o) { this.n=n; this.o=o; }
public Object forBottom(Bottom that) { return that; }
public Object forTopping(Topping that)
{
if(o.equals(that.topping))
that.topping=n;
that.rest.accept(this);
return that;
}
}
class RemoveVisitor implements PieVisitor
{
Object o;
RemoveVisitor(Object o) { this.o=o; }
public Object forBottom(Bottom that) { return new Bottom(); }
public Object forTopping(Topping that)
{
if(o.equals(that.topping))
return that.rest.accept(this);
else return new Topping(that.topping,(Pie)that.rest.accept(this));
}
}
public class TestVisitor
{
public static void main(String[] args)
{
// make a PieManager
PieManager pieManager=new APieManager();
// add some toppings
pieManager.addTopping(new Float(1.2));
pieManager.addTopping(new String("cheese"));
pieManager.addTopping(new String("onions"));
pieManager.addTopping(new String("cheese"));
pieManager.addTopping(new String("onions"));
pieManager.addTopping(new String("peperoni"));
System.out.println("pieManager="+pieManager);
// substitute anchovies for onions
int n=pieManager.substituteTopping(new String("anchovies"),new String("onions"));
System.out.println(n+" pieManager="+pieManager);
// remove the 1.2's
n=pieManager.removeTopping(new Float(1.2));
System.out.println(n+" pieManager="+pieManager);
// how many anchovies do we have?
System.out.println(pieManager.occursTopping(new String("anchovies"))+" anchovies");
}
}
I believe your component Pizza and your abstract decorator PizzaDecorator are supposed to share the same interface, that way each instance of the decorator is capable of the same operations as the core component Pizza.