Related
I am 57 years old. Other than using C# for analysing text data, my knowledge of C# is very limited. However, occasionally I try to learn some other aspects of C#. I also prefer to understand code created for windows applications rather than for console applications.
Could anyone please elaborate on the code given below which is taken from MSDN site with simple practical examples so that I can learn something from it. I think I need to create another class but how to implement it all and call it from a button in C#. Why do they say only derived classes can call 'AddGas'. Thanks in advance.
abstract class Motorcycle
{
// Anyone can call this.
public void StartEngine() {/* Method statements here */ }
// Only derived classes can call this.
protected void AddGas(int gallons) { /* Method statements here */ }
// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }
// Derived classes must implement this.
public abstract double GetTopSpeed();
}
Let that you want to create a specific Motorcycle for instance a Yamaha that has another method that returns the color of the Motorcycle. Instead of creating all the method in Motorcycle from scratch for each motorcycle you want to create you could inherit from it as below:
public class Yamaha : Motorcycle
{
public string GetColor()
{
// ....
return "Red";
}
// When a method in class is marked as abstract,
// all the class that inherit should provide an implementation
// of this method. Otherwise you would get a compilation error.
public double GetTopSpeed()
{
return 200;
}
// When a method is marked as virtual, we have two options for the derived classes.
// 1. Use the implementation provided int the base class.
// 2. Override this implementation, define a method like below and provide
// your implementation.
public override int Drive(int miles, int speed)
{
/* Method statements here */ return 2;
}
}
Furthermore, it's important to note here that you can't instantiate an abstract class (you can't create an object as new Motorcycle()).
Why do they say only derived classes can call 'AddGas' ?
Because AddGas is marked as protected. Reading about access modifiers in C# would make this and other related things more clear.
Abstract classes are just templates or guides for how to make something.
In your example, it's a guide for how to make a Motorcycle. You can't actually create a Motorcycle. You can't go into a dealership and ask for one Motorcycle please.
A Honda? Kawasaki? 150cc? 650cc? What?
Your guide tells you that:
It should be able to be started by someone (*public* void StartEngine())
Internally, should be able to add some petrol - sorry, British - (*protected* void AddPetrol(int litres))
It should be able to be driven by someone (*public* virtual int Drive(int miles, int speed))
It has a top speed that someone can read (*public* abstract double GetTopSpeed())
From this, we can see that anyone can start it, drive it, and get it's top speed.
We can also see that the bike itself can add some petrol to itself (it's an internal combustion engine, after all).
You decide on a Honda. Why? Because that's the first Make that comes to mind. So you ask for that one over there. The salesman tells you ah, that's a good starter one, no frills, no extras, it just works. It's a
public class HondaBasic : Motorcycle {
public override double GetTopSpeed()
{
return 60.0;
{
}
It's cute! You should take it out for a spin...
static void Main(string[] args)
{
// "Aww, it looks like something a child would ride!"
var bike = new HondaBasic();
bike.StartEngine();
// "Wow, is that in MPH or Km/h? Either way I could run faster than that!"
var top = bike.GetTopSpeed();
// "Well, lets take it for a spin, at least..."
bike.StartEngine();
var driven = bike.Drive(3, 30);
}
And so there you go, you took your Honda Basic out for a test drive, for 3 miles at 30 MPH.
I'm going to take liberties here and assume that Drive returns the time actually driven, because I figure time is what you get out when you give something a speed and distance.
Apparently you planned to go out for 3 miles at 30 MPH, and you apparently drove for... 1. Because that's what it said you did...
public virtual int Drive(int miles, int speed) { return 1; }
driven == 1 because the base class just returns 1 all the time! I doubt you managed 3 miles - at 30mph - in 1 minute?second? Not important.
I guess as there's nothing around to call AddGas, it probably ran out after only 1 minute?second?...
Well, that was awful. Why did they even make that model? Ok, what about that sweet thing in the corner? It's shiny! And looks as though it was actually build by people that knew... anything at all, to be honest.
public class KawasakiNinja : Motorcycle {
private int _gas;
public KawasakiNinja()
{
_gas = 100;
}
public override int Drive(int miles, int speed)
{
var timeWhateverValue = miles / speed;
_gas -= timeWhateverValue;
return timeWhateverValue;
}
public override double GetTopSpeed()
{
return 300;
}
protected override void AddGas(int gallons)
{
_gas += gallons;
}
public void FillErUp(int gallons)
{
AddGas(gallons);
}
}
Well ok then... This bike looks to actually be something more than a disposable camera with wheels. It can actually be filled up!
Sounds good! Let's take her for a spin!
static void Main(string[] args)
{
// "Mmm, shiny"
var bike = new KawasakiNinja();
// "Purrs like a kitten!"
bike.StartEngine();
// "How fast?!"
var top = bike.GetTopSpeed();
// "Sweet..."
var driven = bike.Drive(1, 300);
// "Holy cap it really can go 300! I bet it burns up fuel like there's no tomorrow, though! Let's pull over"
bike.FillErUp(50);
// "Enough to get back to the lot"
driven = bike.Drive(1, 40);
}
Quite adventurous of you - burning away a single mile at 300 mph! According to Kawasaki's (our) maths, you drove that in 0 minutes?seconds?
Aaaand it had a way to fill the tank (and, frankly, this model actually had a tank).
So, there's something moderately basic for you.
The abstract class itself just describes how to do things. It may or may not include any actual functionality;
It did specify the Drive method, and implemented it - albeit in a basic way
It specified a GetTopSpeed method, but did not implement it (abstract). That method needs to be implemented in anything made from the abstract class - compiler complains at you if you miss that out, so it's easy enough to not miss
Anything derived from the abstract classes have access to everything the abstract class can do, and, if it's virtual, can override it's implementation. Alternatively, it may actually need to provide an implementation of some kind; where the abstract base knows that it will need to be able to something, but not exactly know what or how.
In the above example, it doesn't make sense that a non-existent bike would have a top speed at all - but we know that any real bike in general will have one - so any real bikes need to provide it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I was studying the Decorator Pattern as documented in GOF.
Please, help me understand the Decorator Pattern. Could someone give a use-case example of where this is useful in the real world?
Decorator pattern achieves a single objective of dynamically adding
responsibilities to any object.
Consider a case of a pizza shop. In the pizza shop they will sell few pizza varieties and they will also provide toppings in the menu. Now imagine a situation wherein if the pizza shop has to provide prices for each combination of pizza and topping. Even if there are four basic pizzas and 8 different toppings, the application would go crazy maintaining all these concrete combination of pizzas and toppings.
Here comes the decorator pattern.
As per the decorator pattern, you will implement toppings as decorators and pizzas will be decorated by those toppings' decorators. Practically each customer would want toppings of his desire and final bill-amount will be composed of the base pizzas and additionally ordered toppings. Each topping decorator would know about the pizzas that it is decorating and it's price. GetPrice() method of Topping object would return cumulative price of both pizza and the topping.
EDIT
Here's a code-example of explanation above.
public abstract class BasePizza
{
protected double myPrice;
public virtual double GetPrice()
{
return this.myPrice;
}
}
public abstract class ToppingsDecorator : BasePizza
{
protected BasePizza pizza;
public ToppingsDecorator(BasePizza pizzaToDecorate)
{
this.pizza = pizzaToDecorate;
}
public override double GetPrice()
{
return (this.pizza.GetPrice() + this.myPrice);
}
}
class Program
{
[STAThread]
static void Main()
{
//Client-code
Margherita pizza = new Margherita();
Console.WriteLine("Plain Margherita: " + pizza.GetPrice().ToString());
ExtraCheeseTopping moreCheese = new ExtraCheeseTopping(pizza);
ExtraCheeseTopping someMoreCheese = new ExtraCheeseTopping(moreCheese);
Console.WriteLine("Plain Margherita with double extra cheese: " + someMoreCheese.GetPrice().ToString());
MushroomTopping moreMushroom = new MushroomTopping(someMoreCheese);
Console.WriteLine("Plain Margherita with double extra cheese with mushroom: " + moreMushroom.GetPrice().ToString());
JalapenoTopping moreJalapeno = new JalapenoTopping(moreMushroom);
Console.WriteLine("Plain Margherita with double extra cheese with mushroom with Jalapeno: " + moreJalapeno.GetPrice().ToString());
Console.ReadLine();
}
}
public class Margherita : BasePizza
{
public Margherita()
{
this.myPrice = 6.99;
}
}
public class Gourmet : BasePizza
{
public Gourmet()
{
this.myPrice = 7.49;
}
}
public class ExtraCheeseTopping : ToppingsDecorator
{
public ExtraCheeseTopping(BasePizza pizzaToDecorate)
: base(pizzaToDecorate)
{
this.myPrice = 0.99;
}
}
public class MushroomTopping : ToppingsDecorator
{
public MushroomTopping(BasePizza pizzaToDecorate)
: base(pizzaToDecorate)
{
this.myPrice = 1.49;
}
}
public class JalapenoTopping : ToppingsDecorator
{
public JalapenoTopping(BasePizza pizzaToDecorate)
: base(pizzaToDecorate)
{
this.myPrice = 1.49;
}
}
This is a simple example of adding new behavior to an existing object dynamically, or the Decorator pattern. Due to the nature of dynamic languages such as Javascript, this pattern becomes part of the language itself.
// Person object that we will be decorating with logging capability
var person = {
name: "Foo",
city: "Bar"
};
// Function that serves as a decorator and dynamically adds the log method to a given object
function MakeLoggable(object) {
object.log = function(property) {
console.log(this[property]);
}
}
// Person is given the dynamic responsibility here
MakeLoggable(person);
// Using the newly added functionality
person.log('name');
It's worth noting that the Java i/o model is based on the decorator pattern. The layering of this reader on top of that reader on top of...is a really real world example of decorator.
Example - Scenario- Let's say you are writing an encryption module. This encryption can encrypt the clear file using DES - Data encryption standard. Similarly, in a system you can have the encryption as AES - Advance encryption standard. Also, you can have the combination of encryption - First DES, then AES. Or you can have first AES, then DES.
Discussion- How will you cater this situation? You cannot keep creating the object of such combinations - for example - AES and DES - total of 4 combinations. Thus, you need to have 4 individual objects This will become complex as the encryption type will increase.
Solution - Keep building up the stack - combinations depending on the need - at run time.
Another advantage of this stack approach is that you can unwind it easily.
Here is the solution - in C++.
Firstly, you need a base class - a fundamental unit of the stack. You can think as the base of the stack. In this example, it is clear file. Let's follow always polymorphism. Make first an interface class of this fundamental unit. This way,you can implement it as you wish. Also, you don't need to have think of dependency while including this fundamental unit.
Here is the interface class -
class IclearData
{
public:
virtual std::string getData() = 0;
virtual ~IclearData() = 0;
};
IclearData::~IclearData()
{
std::cout<<"Destructor called of IclearData"<<std::endl;
}
Now, implement this interface class -
class clearData:public IclearData
{
private:
std::string m_data;
clearData();
void setData(std::string data)
{
m_data = data;
}
public:
std::string getData()
{
return m_data;
}
clearData(std::string data)
{
setData(data);
}
~clearData()
{
std::cout<<"Destructor of clear Data Invoked"<<std::endl;
}
};
Now, let's make a decorator abstract class - that can be extended to create any kind of flavours - here the flavour is the encryption type. This decorator abstract class is related to the base class. Thus, the decorator "is a" kind of interface class. Thus, you need to use inheritance.
class encryptionDecorator: public IclearData
{
protected:
IclearData *p_mclearData;
encryptionDecorator()
{
std::cout<<"Encryption Decorator Abstract class called"<<std::endl;
}
public:
std::string getData()
{
return p_mclearData->getData();
}
encryptionDecorator(IclearData *clearData)
{
p_mclearData = clearData;
}
virtual std::string showDecryptedData() = 0;
virtual ~encryptionDecorator() = 0;
};
encryptionDecorator::~encryptionDecorator()
{
std::cout<<"Encryption Decorator Destructor called"<<std::endl;
}
Now, let's make a concrete decorator class -
Encryption type - AES -
const std::string aesEncrypt = "AES Encrypted ";
class aes: public encryptionDecorator
{
private:
std::string m_aesData;
aes();
public:
aes(IclearData *pClearData): m_aesData(aesEncrypt)
{
p_mclearData = pClearData;
m_aesData.append(p_mclearData->getData());
}
std::string getData()
{
return m_aesData;
}
std::string showDecryptedData(void)
{
m_aesData.erase(0,m_aesData.length());
return m_aesData;
}
};
Now, let's say the decorator type is DES -
const std::string desEncrypt = "DES Encrypted ";
class des: public encryptionDecorator
{
private:
std::string m_desData;
des();
public:
des(IclearData *pClearData): m_desData(desEncrypt)
{
p_mclearData = pClearData;
m_desData.append(p_mclearData->getData());
}
std::string getData(void)
{
return m_desData;
}
std::string showDecryptedData(void)
{
m_desData.erase(0,desEncrypt.length());
return m_desData;
}
};
Let's make a client code to use this decorator class -
int main()
{
IclearData *pData = new clearData("HELLO_CLEAR_DATA");
std::cout<<pData->getData()<<std::endl;
encryptionDecorator *pAesData = new aes(pData);
std::cout<<pAesData->getData()<<std::endl;
encryptionDecorator *pDesData = new des(pAesData);
std::cout<<pDesData->getData()<<std::endl;
/** unwind the decorator stack ***/
std::cout<<pDesData->showDecryptedData()<<std::endl;
delete pDesData;
delete pAesData;
delete pData;
return 0;
}
You will see the following results -
HELLO_CLEAR_DATA
Encryption Decorator Abstract class called
AES Encrypted HELLO_CLEAR_DATA
Encryption Decorator Abstract class called
DES Encrypted AES Encrypted HELLO_CLEAR_DATA
AES Encrypted HELLO_CLEAR_DATA
Encryption Decorator Destructor called
Destructor called of IclearData
Encryption Decorator Destructor called
Destructor called of IclearData
Destructor of clear Data Invoked
Destructor called of IclearData
Here is the UML diagram - Class representation of it. In case, you want to skip the code and focus on the design aspect.
Decorator pattern helps you to change or configure a functionality of your object by chaining with other similar subclasses of this object.
Best example would be InputStream and OutputStream classes in java.io package
File file=new File("target","test.txt");
FileOutputStream fos=new FileOutputStream(file);
BufferedOutputStream bos=new BufferedOutputStream(fos);
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.write(5);
oos.writeBoolean(true);
oos.writeBytes("decorator pattern was here.");
//... then close the streams of course.
What is Decorator Design Pattern in Java.
The formal definition of the Decorator pattern from the GoF book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley) says you can,
"Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality."
Let's say we have a Pizza and we want to decorate it with toppings such as Chicken Masala, Onion and Mozzarella Cheese. Let's see how to implement it in Java ...
Program to demonstrate how to implement Decorator Design Pattern in Java.
See more at: http://www.hubberspot.com/2013/06/decorator-design-pattern-in-java.html#sthash.zKj0xLrR.dpuf
Pizza.java:
<!-- language-all: lang-html -->
package com.hubberspot.designpattern.structural.decorator;
public class Pizza {
public Pizza() {
}
public String description(){
return "Pizza";
}
}
package com.hubberspot.designpattern.structural.decorator;
public abstract class PizzaToppings extends Pizza {
public abstract String description();
}
package com.hubberspot.designpattern.structural.decorator;
public class ChickenMasala extends PizzaToppings {
private Pizza pizza;
public ChickenMasala(Pizza pizza) {
this.pizza = pizza;
}
#Override
public String description() {
return pizza.description() + " with chicken masala, ";
}
}
package com.hubberspot.designpattern.structural.decorator;
public class MozzarellaCheese extends PizzaToppings {
private Pizza pizza;
public MozzarellaCheese(Pizza pizza) {
this.pizza = pizza;
}
#Override
public String description() {
return pizza.description() + "and mozzarella cheese.";
}
}
package com.hubberspot.designpattern.structural.decorator;
public class Onion extends PizzaToppings {
private Pizza pizza;
public Onion(Pizza pizza) {
this.pizza = pizza;
}
#Override
public String description() {
return pizza.description() + "onions, ";
}
}
package com.hubberspot.designpattern.structural.decorator;
public class TestDecorator {
public static void main(String[] args) {
Pizza pizza = new Pizza();
pizza = new ChickenMasala(pizza);
pizza = new Onion(pizza);
pizza = new MozzarellaCheese(pizza);
System.out.println("You're getting " + pizza.description());
}
}
The decorator pattern lets you dynamically add behavior to objects.
Let's take an example where you need to build an app that calculates the price of different kinds of burgers. You need to handle different variations of burgers, such as "large" or "with cheese", each of which has a price relative to the basic burger. E.g. add $10 for burger with cheese, add extra $15 for large burger, etc.
In this case you might be tempted to create subclasses to handle these. We might express this in Ruby as:
class Burger
def price
50
end
end
class BurgerWithCheese < Burger
def price
super + 15
end
end
In the above example, the BurgerWithCheese class inherits from Burger, and overrides the price method to add $15 to the price defined in the super class. You would also create a LargeBurger class and define the price relative to Burger. But you also need to define a new class for the combination of "large" and "with cheese".
Now what happens if we need to serve "burger with fries"? We already have 4 classes to handle those combinations, and we will need to add 4 more to handle all combination of the 3 properties - "large", "with cheese" and "with fries". We need 8 classes now. Add another property and we'll need 16. This will grow as 2^n.
Instead, let's try defining a BurgerDecorator that takes in a Burger object:
class BurgerDecorator
def initialize(burger)
self.burger = burger
end
end
class BurgerWithCheese < BurgerDecorator
def price
self.burger.price + 15
end
end
burger = Burger.new
cheese_burger = BurgerWithCheese.new(burger)
cheese_burger.price # => 65
In the above example, we've created a BurgerDecorator class, from which BurgerWithCheese class inherits. We can also represent the "large" variation by creating LargeBurger class. Now we could define a large burger with cheese at runtime as:
b = LargeBurger.new(cheese_burger)
b.price # => 50 + 15 + 20 = 85
Remember how using inheritance to add the "with fries" variation would involve adding 4 more subclasses? With decorators, we would just create one new class, BurgerWithFries, to handle the new variation and handle this at runtime. Each new property would need just more decorator to cover all the permutations.
PS. This is the short version of an article I wrote about using the Decorator Pattern in Ruby, which you can read if you wish to find out more detailed examples.
Decorator:
Add behaviour to object at run time. Inheritance is the key to achieve this functionality, which is both advantage and disadvantage of this pattern.
It enhances the behaviour of interface.
Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn't intended for object aggregation.
The Decorator class declares a composition relationship to the LCD (Lowest Class Denominator) interface, and this data member is initialized in its constructor.
Decorator is designed to let you add responsibilities to objects without sub-classing
Refer to sourcemaking article for more details.
Decorator (Abstract) : it is an abstract class/interface, which implements the component interface. It contains Component interface. In absence of this class, you need many sub-classes of ConcreteDecorators for different combinations. Composition of component reduces un-necessary sub-classes.
JDK example:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("a.txt")));
while(bis.available()>0)
{
char c = (char)bis.read();
System.out.println("Char: "+c);;
}
Have a look at below SE question for UML diagram and code examples.
Decorator Pattern for IO
Useful articles:
journaldev
wikipedia
Real word example of Decorator pattern: VendingMachineDecorator has been explained #
When to Use the Decorator Pattern?
Beverage beverage = new SugarDecorator(new LemonDecorator(new Tea("Assam Tea")));
beverage.decorateBeverage();
beverage = new SugarDecorator(new LemonDecorator(new Coffee("Cappuccino")));
beverage.decorateBeverage();
In above example, Tea or Coffee ( Beverage) has been decorated by Sugar and Lemon.
Some time back I had refactored a codebase into using Decorator pattern, so I will try to explain the use case.
Lets assume we have a set of services and based on whether the user has acquired licence of particular service, we need to start the service.
All the services have a common interface
interface Service {
String serviceId();
void init() throws Exception;
void start() throws Exception;
void stop() throws Exception;
}
Pre Refactoring
abstract class ServiceSupport implements Service {
public ServiceSupport(String serviceId, LicenseManager licenseManager) {
// assign instance variables
}
#Override
public void init() throws Exception {
if (!licenseManager.isLicenseValid(serviceId)) {
throw new Exception("License not valid for service");
}
// Service initialization logic
}
}
If you observe carefully, ServiceSupport is dependent on LicenseManager. But why should it be dependent on LicenseManager? What if we needed background service which doesn't need to check license information. In the current situation we will have to somehow train LicenseManager to return true for background services.
This approach didn't seem well to me. According to me license check and other logic were orthogonal to each other.
So Decorator Pattern comes to the rescue and here starts refactoring with TDD.
Post Refactoring
class LicensedService implements Service {
private Service service;
public LicensedService(LicenseManager licenseManager, Service service) {
this.service = service;
}
#Override
public void init() {
if (!licenseManager.isLicenseValid(service.serviceId())) {
throw new Exception("License is invalid for service " + service.serviceId());
}
// Delegate init to decorated service
service.init();
}
// override other methods according to requirement
}
// Not concerned with licensing any more :)
abstract class ServiceSupport implements Service {
public ServiceSupport(String serviceId) {
// assign variables
}
#Override
public void init() {
// Service initialization logic
}
}
// The services which need license protection can be decorated with a Licensed service
Service aLicensedService = new LicensedService(new Service1("Service1"), licenseManager);
// Services which don't need license can be created without one and there is no need to pass license related information
Service aBackgroundService = new BackgroundService1("BG-1");
Takeaways
Cohesion of code got better
Unit testing became easier, as don't have to mock licensing when testing ServiceSupport
Don't need to bypass licensing by any special checks for background services
Proper division of responsibilities
Let's take example of PubG. Assault rifles works best with 4x zoom and while we are on it, we would also need compensator and suppressor. It will reduce recoil and reduce firing sound as well as echo. We will need to implement this feature where we will allow players to buy their favourite gun and their accessories. Players can buy the gun or some of the accessory or all of the accessory and they would be charged accordingly.
Let's see how decorator pattern is applied here:
Suppose someone wants to buy SCAR-L with all three accessories mentioned above.
Take an object of SCAR-L
Decorate (or add) the SCAR-L with 4x zoom object
Decorate the SCAR-L with suppressor object
Decorate the SCAR-L with compressor object
Call the cost method and let each object delegate to add on the cost
using cost method of accessories
This will lead to a class diagram like this:
Now, we can have classes like this:
public abstract class Gun {
private Double cost;
public Double getCost() {
return cost;
}
}
public abstract class GunAccessories extends Gun { }
public class Scarl extends Gun {
public Scarl() {
cost = 100;
}
}
public class Suppressor extends GunAccessories {
Gun gun;
public Suppressor(Gun gun) {
cost = 5;
this.gun = gun;
}
public double getCost(){
return cost + gun.getCost();
}
}
public class GunShop{
public static void main(String args[]){
Gun scarl = new Scarl();
scarl = new Supressor(scarl);
System.out.println("Price is "+scarl.getCost());
}
}
We can similarly add other accessories too and decorate our Gun.
Reference:
https://nulpointerexception.com/2019/05/05/a-beginner-guide-to-decorator-pattern/
Decorators are just a compositional alternative to subclassing.
The common example from the original book on this topic, that everyone mentions, is with a text processing application.
Lets say you write a paragraph. You highlight it yellow. You italicize one sentence. You bolden half of the italicized sentence, and half of the next sentence too. You increase the font size of one of the italicized & bold letters. You change the font style of half the highlighted portion, some of it running over into the italicized portion, some not...
So I'm going to ask you how you'd implement that functionality. You start out with a class for a simple, undecorated letter. What do you do next?
I'm going to assume you would not use subclassing. You would need such a complex, convoluted hierarchy of multiple inheritance to achieve all the combinations I described and more, that subclassing and multiple inheritance just would be absurd. And I think that needs no explanation.
What you'd probably suggest is just packing all these properties into your letter object. Properties to define the font style, the size, the highlighting, bold, italicized, the list goes on. Every kind of property you could add to a letter object, you've got a property in your letter class for it.
So what are the problems with this property based approach?
now your class is bloated, it takes up a giant amount of memory. It has all these unnecessary properties associated with it, most that it will never use. Most letters are just... letters. Not decorated.
The data of your letter class is being used in a way that is completely exposed, your class is just a glorified struct. You have a bunch of getters and setters for all these properties. Outside code accesses those setters and modifies the graphical appearance of your object. There's tight coupling between your object and the outside code.
Everything is packed into one place, it's not modular. It's just going to be a bloated, interconnected bundle of code. That's going to be true in the outside code that handles your letter object as well, too.
Fundamentally it's a question of object oriented design, proper encapsulation and separation of concerns.
Now, let's just take it for granted we wanted to use better OO design principles. We want to use encapsulation, we want to maintain loose coupling between the outside code and our letter class. We wanted to minimize our letter objects memory footprint. How...? We can't use subclassing...
So we use decorators, which are a compositional approach to object oriented design - it's sort of the opposite of a top-down, subclassing approach. You wrap these letter objects with more functionality at runtime, building on top of them.
So that's what the decorator pattern is - it's a compositional alternative to subclassing. In our example you add a decorator to the letter object that needs highlighting. You can combine any number of decorators in an arbitrary number of ways, and wrap them all around a given letter. The decorator interface is always transparent, so you still treat these letters the same from the outside.
Any time you need to augment functionality in a way that's arbitrary and recombinable, consider this approach. Multiple inheritance runs into all kinds of problems, it just isn't scalable.
There is a example on Wikipedia about decorating a window with scrollbar:
http://en.wikipedia.org/wiki/Decorator_pattern
Here is another very 'real world' example of "Team member, team lead and manager", which illustrates that decorator pattern is irreplaceable with simple inheritance:
https://zishanbilal.wordpress.com/2011/04/28/design-patterns-by-examples-decorator-pattern/
Decorator pattern achieves a single objective of dynamically adding responsibilities to any object.
Java I/O Model is based on decorator pattern.
Decorator Design Pattern:
This pattern helps to modify the characteristics of an object at runtime. It provides different flavours to an object and gives flexibility to choose what ingredients we want to use in that flavour.
Real Life Example:
Lets say you have a main cabin seat in a flight. Now you are allowed to choose multiple amenities with the seat. Each amenity has its own cost associated with it. Now if a user chooses Wifi and premium food, he/she will be charged for seat + wifi + premium food.
In this case decorator design pattern can really help us. Visit the above link to understand more about decorator pattern and implementation of one real life example.
I am attempting to apply the Strategy pattern to a particular situation, but am having an issue with how to avoid coupling each concrete strategy to the context object providing data for it. The following is a simplified case of a pattern that occurs a few different ways, but should be handled in a similar way.
We have an object Acquisition that provides data relevant to a specific frame of time - basically a bunch of external data collected using different pieces of hardware. It's already too large because of the amount of data it contains, so I don't want to give it any further responsibility. We now need to take some of this data, and based on some configuration send a corresponding voltage to a piece of hardware.
So, imagine the following (much simplified) classes:
class Acquisition
{
public Int32 IntegrationTime { get; set; }
public Double Battery { get; set; }
public Double Signal { get; set; }
}
interface IAnalogOutputter
{
double getVoltage(Acquisition acq);
}
class BatteryAnalogOutputter : IAnalogOutputter
{
double getVoltage(Acquisition acq)
{
return acq.Battery;
}
}
Now, every concrete strategy class has to be coupled to my Acquisition class, which is also one of the most likely classes to be modified since it's core to our application. This is still an improvement over the old design, which was a giant switch statement inside the Acquisition class. Each type of data may have a different conversion method (while Battery is a simple pass-through, others are not at all that simple), so I feel Strategy pattern or similar should be the way to go.
I will also note that in the final implementation, IAnalogOutputter would be an abstract class instead of an interface. These classes will be in a list that is configurable by the user and serialized to an XML file. The list must be editable at runtime and remembered, so Serializable must be part of our final solution. In case it makes a difference.
How can I ensure each implementation class gets the data it needs to work, without tying it to one of my most important classes? Or am I approaching this sort of problem in the completely wrong manner?
Strategy Pattern encapsulates a - usually complex - operation/calculation.
The voltage you want to return is dependent on
pieces of configuration
Some of the acquisition data
So I would put these into another class and pass it to strategy implementors.
Also in terms of serialisation, you do not have serialise the strategy classes, perhaps only their name or type name.
UPDATE
Well, it seems that your implementations need only one piece of the acquisition data. That is a bit unusual for a strategy pattern - but I do not believe it fits Visitor better so strategy is fine. I would create a class which has as property, acquisition data (perhaps inherits from it) in addition to configuration that implementors need.
One thing you could do is use factory methods to construct your Strategies. Your individual strategies can take in their constructor only the individual data elements they need, and the factory method is the only thing that needs to know how to fill in that data given an Acquisition object. Something like this:
public class OutputterFactory
{
public static IAnalogOutputter CreateBatteryAnalogOutputter(Acquisition acq)
{
return new BatteryANalogOutputter(acq.Battery);
}
}
Ok, I hate to not give someone else the credit here, but I found a hybrid solution that works very well for my purposes. It serializes perfectly, and greatly simplifies the addition of new output types. The key was a single interface, IOutputValueProvider. Also note how easily this pattern handles the retrieval of varying ways of storing the data (such as a Dictionary instead of a parameter).
interface IOutputValueProvider
{
Double GetBattery();
Double GetSignal();
Int32 GetIntegrationTime();
Double GetDictionaryValue(String key);
}
interface IAnalogOutputter
{
double getVoltage(IOutputValueProvider provider);
}
class BatteryAnalogOutputter : IAnalogOutputter
{
double getVoltage(IOutputValueProvider provider)
{
return provider.GetBattery();
}
}
class DictionaryValueOutputter : IAnalogOutputter
{
public String DictionaryKey { get; set; }
public double getVoltage(IOutputValueProvider provider)
{
return provider.GetDictionaryValue(DictionaryKey);
}
}
So then, I just need to ensure Acquisition implements the interface:
class Acquisition : IOutputValueProvider
{
public Int32 IntegrationTime { get; set; }
public Double Battery { get; set; }
public Double Signal { get; set; }
public Dictionary<String, Double> DictionaryValues;
public double GetBattery() { return Battery;}
public double GetSignal() { return Signal; }
public int GetIntegrationTime() { return IntegrationTime; }
public double GetDictionaryValue(String key)
{
Double d = 0.0;
return DictionaryValues.TryGetValue(key, out d) ? d : 0.0;
}
}
This isn't perfect, since now there's a gigantic interface that must be maintained and some duplicate code in Acquisition, but there's a heck of a lot less risk of something being changed affecting the other parts of my application. It also allows me to start subclassing Acquisition without having to change some of these external pieces. I hope this will help some others in similar situations.
I am use to designing my applications using a more database driven approach and now I would like to start from the model. I have the following requirements and would like to get your take on it. It's basically an Activity with points associated with it.
Activity with Super 30 Doctor
Minimum 4 per month
Subtract a point if you do not hit the minimum (4)
1 Point or 2 Points if you go over 6 per month
2 Points when with a local advocate
Activity with 120 Doctor
.5 Points
Activity with Partnership
2 Points
Activity with Follow-Up Partnership Meeting
2 Points
So, I'm trying to decided if I use an inheritance hiearchy here for each activity type or an enumeration off of the activity. So, is each activity responsible for calculating their points (but in some instances then need to know the total activity count to decide) or do I have some scorer component know all the logic.
Any ideas would be great!
I have this design thus far, but I do not know where to handle the Super 30 rules:
public abstract class ActivityBase {
public int Id { get; set; }
public DateTime Date { get; set; }
public abstract double CalculatePoints();
}
public class SuperThirtyActivity : ActivityBase {
public bool WithCE { get; set; }
public bool WithLocalAdvocate { get; set; }
public override double CalculatePoints() {
if (Date.Month == 3 && Date.AddDays(7).Month == 4)
return 1;
else if (WithCE || WithLocalAdvocate)
return 2;
else
return 1;
}
}
public class OneTwentyActivity : ActivityBase {
public override double CalculatePoints() {
return .5;
}
}
public class PartnershipActivity : ActivityBase {
public override double CalculatePoints() {
return 2;
}
}
Now to handle the Super 30 rules, I thought of introducing the following class. However, some of the domain logic is leaking in here. Is this ok or any other ideas??
public class Scorer {
public double CalculateScore(IEnumerable<ActivityBase> activities) {
var score = activities.Select(a => a.CalculatePoints()).Sum();
var count = activities.Count(a => a is SuperThirtyActivity);
if (count < 4)
score--;
else if (count > 6)
score += count;
return score;
}
}
If the activity base class will contain no logic, I recommend making an IActivity interface and make 4 classes to implement it instead of inheritance. IActivity should have a method like CalculatePoints to be implemented by every realizing class.
If you are not going to check for Activity types anywhere in your application I mean if you will never have code like :
if (activity is PartnershipActivity){
//do something
}
else if (activity is FollowUpActivity) {
// do something else
}
and if you are sure there will be no new activity types introduced into the application in the future you may then consider making one Activity class with enum field as you said and do all the checks and calculations you mentioned in its business logic.
Since some of the points are based on aggregated activities, it looks like there is another concept that is not being captured in the object model, ActivityCollection. It is hinted at in the parameter to Scorer.CalculateScore, but perhaps it needs to be made explicit. The ActivityCollection could then calculate the scores since it is holding all of the information necessary.
On the other hand, the Scorer object can probably serve that role just as well. It is OK that the domain logic is in the Scorer object, since it is only the logic necessary for Scorer to do exactly what its name implies. If you keep Scorer, but move the point values from the activity classes into it, then that structure may serve just as well, if not better.
One of the most important aspects of OOP is data hiding. Can somebody explain using a simple piece of code what data hiding is exactly and why we need it?
Data or Information Hiding is a design principal proposed by David Paranas.
It says that you should hide the
design decisions in one part of the
program that are likely to be changed
from other parts of the program, there
by protecting the other parts from
being affected by the changes in the
first part.
Encapsulation is programming language feature which enables data hiding.
However note that you can do data\information hiding even without encapsulation. For example using modules or functions in non Object Oriented programming languages. Thus encapsulation is not data hiding but only a means of achieving it.
While doing encapsulation if you ignore the underlying principal then you will not have a good design. For example consider this class -
public class ActionHistory
{
private string[] _actionHistory;
public string[] HistoryItems
{
get{return _actionHistory; }
set{ _actionHistory = value; }
}
}
This calls encapsulates an array. But it does not hide the design decision of using a string[] as an internal storage. If we want to change the internal storage later on it will affect the code using this class as well.
Better design would be -
public class ActionHistory
{
private string[] _actionHistory;
public IEnumerable<string> HistoryItems
{
get{return _actionHistory; }
}
}
I'm guessing by data hiding you mean something like encapsulation or having a variable within an object and only exposing it by get and modify methods, usually when you want to enforce some logic to do with setting a value?
public class Customer
{
private decimal _accountBalance;
public decimal GetBalance()
{
return _accountBalance;
}
public void AddCharge(decimal charge)
{
_accountBalance += charge;
if (_accountBalance < 0)
{
throw new ArgumentException(
"The charge cannot put the customer in credit");
}
}
}
I.e. in this example, I'm allowing the consuming class to get the balance of the Customer, but I'm not allowing them to set it directly. However I've exposed a method that allows me to modify the _accountBalance within the class instance by adding to it via a charge in an AddCharge method.
Here's an article you may find useful.
Information hiding (or more accurately encapsulation) is the practice of restricting direct access to your information on a class. We use getters/setters or more advanced constructs in C# called properties.
This lets us govern how the data is accessed, so we can sanitize inputs and format outputs later if it's required.
The idea is on any public interface, we cannot trust the calling body to do the right thing, so if you make sure it can ONLY do the right thing, you'll have less problems.
Example:
public class InformationHiding
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
/// This example ensures you can't have a negative age
/// as this would probably mess up logic somewhere in
/// this class.
private int _age;
public int Age
{
get { return _age; }
set { if (value < 0) { _age = 0; } else { _age = value; } }
}
}
Imagine that the users of your class are trying to come up with ways to make your class no longer fulfill its contract. For instance, your Banking object may have a contract that ensures that all Transactions are recorded in a log. Suppose mutation of the Bank's TransactionLog were publically accessible; now a consuming class could initiate suspect transactions and modify the log to remove the records.
This is an extreme example, but the basic principles remain the same. It's up to the class author to maintain the contractual obligations of the class and this means you either need to have weak contractual obligations (reducing the usefulness of your class) or you need to be very careful about how your state can be mutated.
What is data hiding?
Here's an example:
public class Vehicle
{
private bool isEngineStarted;
private void StartEngine()
{
// Code here.
this.isEngineStarted = true;
}
public void GoToLocation(Location location)
{
if (!this.isEngineStarted)
{
this.StartEngine();
}
// Code here: move to a new location.
}
}
As you see, the isEngineStarted field is private, ie. accessible from the class itself. In fact, when calling an object of type Vehicle, we do need to move the vehicle to a location, but don't need to know how this will be done. For example, it doesn't matter, for the caller object, if the engine is started or not: if it's not, it's to the Vehicle object to start it before moving to a location.
Why do we need this?
Mostly to make the code easier to read and to use. Classes may have dozens or hundreds of fields and properties that are used only by them. Exposing all those fields and properties to the outside world will be confusing.
Another reason is that it is easier to control a state of a private field/property. For example, in the sample code above, imagine StartEngine is performing some tasks, then assigning true to this.isEngineStarted. If isEngineStarted is public, another class would be able to set it to true, without performing tasks made by StartEngine. In this case, the value of isEngineStarted will be unreliable.
Data Hiding is defined as hiding a base class method in a derived class by naming the new class method the same name as the base class method.
class Person
{
public string AnswerGreeting()
{
return "Hi, I'm doing well. And you?";
}
}
class Employee : Person
{
new public string AnswerGreeting()
{
"Hi, and welcome to our resort.";
}
}
In this c# code, the new keyword prevents the compiler from giving a warning that the base class implementation of AnswerGreeting is being hidden by the implementation of a method with the same name in the derived class. Also known as "data hiding by inheritance".
By data hiding you are presumably referring to encapsulation. Encapsulation is defined by wikipedia as follows:
Encapsulation conceals the functional
details of a class from objects that
send messages to it.
To explain a bit further, when you design a class you can design public and private members. The class exposes its public members to other code in the program, but only the code written in the class can access the private members.
In this way a class exposes a public interface but can hide the implementation of that interface, which can include hiding how the data that the class holds is implemented.
Here is an example of a simple mathematical angle class that exposes values for both degrees and radians, but the actual storage format of the data is hidden and can be changed in the future without breaking the rest of the program.
public class Angle
{
private double _angleInDegrees;
public double Degrees
{
get
{
return _angleInDegrees;
}
set
{
_angleInDegrees = value;
}
}
public double Radians
{
get
{
return _angleInDegrees * PI / 180;
}
set
{
_angleInDegrees = value * 180 / PI;
}
}
}