473,379 Members | 1,511 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Learning patterns... Decorator

Hi

I'm trying to learn patterns, which I hope to use in my PHP code,
although I'm finding it hard to get any real impression of how patterns
fit in properly, I've done the following test code for Decorator pattern
and want to know:

a) is it correct, this is decorator pattern?
b) how would i use this in practice with a database, eg. how would i
store the 'attributes' in tables, and how would the 'pattern' be used in
conjunction?

Any hints, tips, pointers to examples would be appreciated:

<?php
interface IProduct {

public function getName();
public function cost();

}

class CProduct implements IProduct {

private $_name = 'Product';

public function getName() {
return $this->_name;
}

public function cost() {
return 10.99;
}

}

class CWhiteProduct implements IProduct {

private $Product = null;

public function __construct( $product ) {
$this->Product = $product;
}

public function getName() {
return 'White ' . $this->Product->getName();
}

public function cost() {
return $this->Product->cost() + 1.50;
}

}

class CLargeProduct implements IProduct {

private $Product = null;

public function __construct ( $product ) {
$this->Product = $product;
}

public function getName() {
return 'Large ' . $this->Product->getName();
}

public function cost() {
return $this->Product->cost() + 3.00;
}

}

$product = new CProduct();
echo "<p>A product is {$product->cost()}</p>";

$largeproduct = new CLargeProduct( $product );
echo "<p>A large product is {$largeproduct->cost()}</p>";

$whiteproduct = new CWhiteProduct( $product );
echo "<p>A white product is {$whiteproduct->cost()}</p>";

$largewhiteproduct = new CLargeProduct( $whiteproduct );
echo "<p>A {$largewhiteproduct->getName()} product is
{$largewhiteproduct->cost()}</p>";

?>
Sep 28 '07 #1
9 1605
I'm trying to learn patterns, which I hope to use in my PHP code,
although I'm finding it hard to get any real impression of how patterns
fit in properly, I've done the following test code for Decorator pattern
and want to know:

a) is it correct, this is decorator pattern?
b) how would i use this in practice with a database, eg. how would i
store the 'attributes' in tables, and how would the 'pattern' be used in
conjunction?

Any hints, tips, pointers to examples would be appreciated:
The GOF book ("Design Patterns") is quite clear, I think.

<snipped example>

A decorator is a class that adds functionality at runtime. Functionality
you could add to your objects in that way are things like spread
payment, discount conditions, etc. The point of the pattern is that you
can add responsibility to specific objects instead of whole classes. It
is an alternative to subclassing (your example was subclassing).

Best regards,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Sep 28 '07 #2
On Fri, 28 Sep 2007 10:03:05 +0200, Willem Bogaerts
<w.********@kratz.maardanzonderditstuk.nlwrote:
>I'm trying to learn patterns, which I hope to use in my PHP code,
although I'm finding it hard to get any real impression of how patterns
fit in properly, I've done the following test code for Decorator pattern
and want to know:

a) is it correct, this is decorator pattern?
b) how would i use this in practice with a database, eg. how would i
store the 'attributes' in tables, and how would the 'pattern' be used in
conjunction?

Any hints, tips, pointers to examples would be appreciated:
The GOF book ("Design Patterns") is quite clear, I think.

<snipped example>

A decorator is a class that adds functionality at runtime. Functionality
you could add to your objects in that way are things like spread
payment, discount conditions, etc. The point of the pattern is that you
can add responsibility to specific objects instead of whole classes. It
is an alternative to subclassing (your example was subclassing).
Yup, and Matt Zandstra has a pretty handy real decorator pattern example
in PHP in his book ('PHP 5 Objects, Patterns, and Practice' I believe).

--
Rik Wasmus
Sep 28 '07 #3
Rik Wasmus wrote:
On Fri, 28 Sep 2007 10:03:05 +0200, Willem Bogaerts
<w.********@kratz.maardanzonderditstuk.nlwrote:
>>I'm trying to learn patterns, which I hope to use in my PHP code,
although I'm finding it hard to get any real impression of how patterns
fit in properly, I've done the following test code for Decorator pattern
and want to know:

a) is it correct, this is decorator pattern?
b) how would i use this in practice with a database, eg. how would i
store the 'attributes' in tables, and how would the 'pattern' be used in
conjunction?

Any hints, tips, pointers to examples would be appreciated:
The GOF book ("Design Patterns") is quite clear, I think.

<snipped example>

A decorator is a class that adds functionality at runtime. Functionality
you could add to your objects in that way are things like spread
payment, discount conditions, etc. The point of the pattern is that you
can add responsibility to specific objects instead of whole classes. It
is an alternative to subclassing (your example was subclassing).

Yup, and Matt Zandstra has a pretty handy real decorator pattern example
in PHP in his book ('PHP 5 Objects, Patterns, and Practice' I believe).
Are you sure I was subclassing? I thought I would have to use
'extends' to subclass.

I'm creating a new class that implemented same interface and passing
a base class in the constructor, so that is sub-classing?

I thought subclassing would be like:

class WhiteProduct extends Product {
... blah
... blah
}

I thought maybe I could have a CLargeProduct that got it's values from
a database somehow so it was pretty 'generic' and it's values applied
at run-time based on the db content? And the cost() function wraps
around or 'decorates' the base passed through the constructor???

You're probably right, I'm just trying to get a better understanding as
OOP isn't my scene but I would like it to be.

I'm probably very confused ;)
Sep 28 '07 #4
Are you sure I was subclassing? I thought I would have to use
'extends' to subclass.
An interface is a purely abstract class. The syntax is different, but
you are still subclassing a (very) generic thing.
I thought maybe I could have a CLargeProduct that got it's values from
a database somehow so it was pretty 'generic' and it's values applied
at run-time based on the db content? And the cost() function wraps
around or 'decorates' the base passed through the constructor???
The GOF book speaks about "adding responsibility dynamically". The
CLargeProduct class does not add anything dynamically ("at runtime") and
the responsibility is to hand out a value. I don't think a product class
should even be aware of the existence of a database.

Best regards,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Sep 28 '07 #5
Willem Bogaerts wrote:
>Are you sure I was subclassing? I thought I would have to use
'extends' to subclass.

An interface is a purely abstract class. The syntax is different, but
you are still subclassing a (very) generic thing.
yes, i was reading that 'programming to an interface' really means an
interface or abstract class.
The GOF book speaks about "adding responsibility dynamically". The
CLargeProduct class does not add anything dynamically ("at runtime") and
the responsibility is to hand out a value. I don't think a product class
should even be aware of the existence of a database.
I wasn't thinking of putting any database login in the decorator itself,
rather this would be done separately and i wouldn't specifically have
such a thing as CWhiteProduct, rather it would be CColourDecorator that
would apply the 'adjusted' cost for the painting job.

I actually found this article now:
http://www.devshed.com/c/a/PHP/Worki...attern-in-PHP/

I think I see what you mean, this does use 'extends' but doesn't add any
new methods and uses same parent calling technique, so is
decorat/subclass a very subtle difference, ie. if you add a new method
not in the parent, it then basically becomes sub-classing?

The thing I'm trying to get to really is how the database data should be
structured and how the actual PHP code would utilise 'attribute' values
such as 'white' and how the code would be structured in the PHP to then
'decorate' my product to find it's real value.

eg. website may have 'Coat' product, might have drop-down 'White',
'Furry', in the db white may cost 1.00 more, if you want it furry, might
be an extra 2.00

what is an object orientated approaching to extracting and processing
this against a base 'product' object??

normally you'd be using switch and if's and things to do things if 'some
attribute' is returned in a dataset, but i want to practice getting rid
of big switch/if type structures.
Sep 28 '07 #6
I think I see what you mean, this does use 'extends' but doesn't add any
new methods and uses same parent calling technique, so is
decorat/subclass a very subtle difference, ie. if you add a new method
not in the parent, it then basically becomes sub-classing?
It is the parent's responsibility to provide a cost. Hence the cost()
method. _HOW_ that cost is determined is an internal responsibility
(which may be met by delegating actions to other classes like
databases). All your subclasses have therefore the same responsibility:
provide a cost. Your subclasses "specialize" in the way this
responsibility is met.

The point of a decorator is that you may need to add responsibility to
an existing instance, so after you have given it a class. This is
impossible to do using subclasses.
The thing I'm trying to get to really is how the database data should be
structured and how the actual PHP code would utilise 'attribute' values
such as 'white' and how the code would be structured in the PHP to then
'decorate' my product to find it's real value.

eg. website may have 'Coat' product, might have drop-down 'White',
'Furry', in the db white may cost 1.00 more, if you want it furry, might
be an extra 2.00
There are many ways to do that. Some people incorporate all the details
in the product name, some people use categories, versions, etc. You can
then either calculate the price at runtime with the given versions or
have price entries for all possibilities. I would suggest the latter,
because not all combinations thinkable are necessary deliverable.

Best regards
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Sep 28 '07 #7
Willem Bogaerts wrote:
There are many ways to do that. Some people incorporate all the details
in the product name, some people use categories, versions, etc. You can
then either calculate the price at runtime with the given versions or
have price entries for all possibilities. I would suggest the latter,
because not all combinations thinkable are necessary deliverable.

Best regards
Thanks Willem, I'll have to have a further play with classes/patterns
and look for more examples. The point is, I'm trying to justify using
them to myself over functional programming, at the moment I try building
class based projects and most of the time they just end up being more
confusing, taking longer and not really adding much benefit.

But obviously, I'm doing them wrong, but have no peer to show me what I
should be doing :-(

Cheers.

Sep 28 '07 #8
Thanks Willem, I'll have to have a further play with classes/patterns
and look for more examples. The point is, I'm trying to justify using
them to myself over functional programming, at the moment I try building
class based projects and most of the time they just end up being more
confusing, taking longer and not really adding much benefit.
One word of advice: patterns are not holy. Don't try to force your code
into a pattern. Even if an existing pattern would be appropriate, you
might choose the wrong one. Read about patterns and see _why_ they are
useful. You may very well come up with a number of patterns of your own.
Some programming languages even create a need for them.
For me, patterns emerge from my code. And as my code is not that unique,
many patterns are recognizable from textbooks as well. Reading about
patterns helps you to identify them if they emerge. But if they don't
emerge, no problem.

And do not be afraid to change things later. No program is perfect and
even if it were today, it wouldn't be tomorrow. If I may suggest a good
read, read "refactoring" by Martin Fowler. It features a nice "let's put
a class statement around this" program and it shows how to morph it into
a real object-oriented one.

Good luck,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Sep 28 '07 #9
Thanks Willem! Going to be a long journey :-)

Willem Bogaerts wrote:
>Thanks Willem, I'll have to have a further play with classes/patterns
and look for more examples. The point is, I'm trying to justify using
them to myself over functional programming, at the moment I try building
class based projects and most of the time they just end up being more
confusing, taking longer and not really adding much benefit.

One word of advice: patterns are not holy. Don't try to force your code
into a pattern. Even if an existing pattern would be appropriate, you
might choose the wrong one. Read about patterns and see _why_ they are
useful. You may very well come up with a number of patterns of your own.
Some programming languages even create a need for them.
For me, patterns emerge from my code. And as my code is not that unique,
many patterns are recognizable from textbooks as well. Reading about
patterns helps you to identify them if they emerge. But if they don't
emerge, no problem.

And do not be afraid to change things later. No program is perfect and
even if it were today, it wouldn't be tomorrow. If I may suggest a good
read, read "refactoring" by Martin Fowler. It features a nice "let's put
a class statement around this" program and it shows how to morph it into
a real object-oriented one.

Good luck,
Sep 28 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Tony Ha | last post by:
Hello I am learning Python for in the pass ten months, and have brought a few books about Python. Most of them are good books by its only right, and all of them only teach you how to write...
8
by: NKOBAYE027 | last post by:
Hi Folks: Can anyone direct me to a good resource on design patterns. I'd like to use them for a project I'm working on regarding set theory - in particular I'd like to use the Decorator pattern to...
2
by: Tim Smith | last post by:
Dear All, Silly question, but I am having trouble understanding the diagram on the inside back cover entitled "Design Pattern Relationships." It shows the relationships between all of the...
11
by: FluffyCat | last post by:
In Febraury - April of 2002 I put together in Java examples of all 23 of the classic "Gang Of Four" design patterns for my website. Partly I wanted to get a better understanding of those patterns....
12
by: Steve Jorgensen | last post by:
The classing Visual Basic and VBA support for polymorphism, let's face it, is a bit on the weak side, and built-in support for inheritance is non-existent. This little essay is about some patterns...
3
by: yb | last post by:
Hi, I just started reading design patterns and looking at the Lexi example. I'm very new to this so please bear with me. I understand the Decorator pattern, but a bit confused by the Maze...
12
by: Jeff | last post by:
I'm just getting up to speed on OOP patterns (e.g, MVC) and I'm wondering how closely they are followed out in the real world. Do those of you who use them try to follow them as closely as possible...
0
by: JosAH | last post by:
Greetings, last week we talked a bit about the Visitor design pattern. This week we'll talk a bit about additional functionality that is sometimes wanted, i.e. the functionality is optional....
9
by: Christian Hackl | last post by:
Hi! I've got a design question related to the combination of the NVI idiom (non-virtual interfaces, ) and popular object-oriented patterns such as Proxy or Decorator, i.e. those which have the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.