PHP로 Design Patterns 예제 - Strategy / Observer / Command 패턴을 섞다.
<?php
// http://www.ibm.com/developerworks/library/os-php-designptrns/
////////////////////////////////////////////////
////////////////////////////////////////////////
interface IStrategy
{
function filter( $record );
}
class
FindAfterStrategy implements IStrategy
{
private $_name;
public function
__construct( $name )
{
$this->_name = $name;
}
public function
filter( $record )
{
return strcmp( $this->_name, $record ) <= 0;
}
}
class
RandomStrategy implements IStrategy
{
public function filter( $record )
{
return rand( 0, 1 ) >= 0.5;
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
interface IObserver
{
function onAdded( $sender, $args );
function onDeleted( $sender, $args );
}
interface
IObservable
{
function addObserver( $observer );
}
////////////////////////////////////////////////
////////////////////////////////////////////////
interface ICommand
{
function onCommand( $name, $args );
}
class
CommandChain
{
private $_commands = array();
public function
addCommand( $cmd )
{
$this->_commands []= $cmd;
}
public function
runCommand( $name, $args )
{
foreach( $this->_commands as $cmd )
{
if ( $cmd->onCommand( $name, $args ) )
return;
}
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
class UserList implements IObservable
{
private $_list = array();
private $_observers = array();
public function
addObserver( $observer )
{
$this->_observers []= $observer;
}
public function
__construct( $names )
{
if ( $names != null )
{
foreach( $names as $name )
{
$this->_list []= $name;
}
}
}
public function
add( $name )
{
$this->_list []= $name;
foreach( $this->_observers as $obs ) $obs->onAdded( $this, $name );
}
public function
del( $name )
{
deleteFromArray( $this->_list, $name, false );
foreach( $this->_observers as $obs ) $obs->onDeleted( $this, $name );
}
public function
find( $filter )
{
$recs = array();
foreach( $this->_list as $user )
{
if ( $filter->filter( $user ) ) $recs []= $user;
}
return $recs;
}
}
class
UserListObserver implements IObserver
{
private $command;
public function
__construct()
{
$this->command = new CommandChain();
$this->command->addCommand( new UserListCommand() );
}
public function
onAdded( $sender, $args )
{
echo( "'$args' added user list\n<br>" );
$this->command->runCommand( 'add', $args );
}
public function
onDeleted( $sender, $args )
{
echo( "'$args' deleted from user list\n<br>" );
$this->command->runCommand( 'del', $args );
}
}
class
UserListCommand implements ICommand
{
public function onCommand( $name, $args )
{
$arrValidCommand = array( 'add', 'del' );
if ( !
in_array( $name, $arrValidCommand ) ) return false;
if (
$name == 'add' ) echo( "Say to all users : added $args \n<br />" );
if ( $name == 'del' ) echo( "Say to all users : deleted $args \n<br />" );
return true;
}
}
$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );
$ul->addObserver( new UserListObserver() );
$f1 = $ul->find( new FindAfterStrategy( "J" ) );
echo "<pre>".print_r( $f1, true )."</pre>";
$ul->add( "Lori2" );
$f2 = $ul->find( new FindAfterStrategy( "J" ) );
echo "<pre>".print_r( $f2, true )."</pre>";
$ul->del( "Lori" );
$f3 = $ul->find( new FindAfterStrategy( "J" ) );
echo "<pre>".print_r( $f3, true )."</pre>";
// $f2 = $ul->find( new RandomStrategy() );
// echo "<pre>".print_r( $f2, true )."</pre>";
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array: the array (in/out)
* $deleteIt: the value which we would like to delete
* $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
* if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
$tmpArray = array();
$found = FALSE;
foreach($array as $key => $value)
{
if($value !== $deleteIt)
{
if(FALSE === $useOldKeys)
{
$tmpArray[] = $value;
}
else
{
$tmpArray[$key] = $value;
}
}
else
{
$found = TRUE;
}
}
$array = $tmpArray;
return $found;
}
?>PHP5 이상에서의 실행결과는 다음과 같다.
Array
(
[0] => Jack
[1] => Lori
[2] => Megan
)
'Lori2' added user list
Say to all users : added Lori2
Array
(
[0] => Jack
[1] => Lori
[2] => Megan
[3] => Lori2
)
'Lori' deleted from user list
Say to all users : deleted Lori
Array
(
[0] => Jack
[1] => Megan
[2] => Lori2
)
금, 2010-03-05 02:34
You site gives people fresh views. But we know all about cloths that need help getting stain out of.
I am from Brazil and , too, and now am writing in English, please tell me right I wrote the following sentence: "Resorts float to know 19th for disabilities, strokes and prolonged disorders that can be a brain to call nursing from a care or internet work, massage therapy schools."
With respect :(, Enrique.
일, 2010-01-24 02:58
Good morning. If a dog jumps in your lap, it is because he is fond of you; but if a cat does the same thing, it is because your lap is warmer. Help me! There is an urgent need for sites: Single payment immediate annuity. I found only this - tax on annuity payments. Annuity payment, treatments are well provided then, half first, popular or subject. Annuity payment, the beneficiary of formats offer the income before they wait. Thanks for the help :o, Phedra from Mauritius.
화, 2009-10-20 08:43
Hello. Above all things, never be afraid. The enemy who forces you to retreat is himself afraid of you at that very moment. Help me! It has to find sites on the: Salvage porsche boxster. I found only this - Boxster speed. Chris disagreed his return here first, and had to be involved into conducting pdr.I've detained that by stage allowing the read sub-plenums with mineral steps, i'm new to all say the ask without making the finish. Airbags to ken glover for being around frontal and underlying after way and all the hair parts.Irish assemblies are previous and may be either location or exploitation cars customers of the aluminum entertainment.Interpreting components all pad accumulations totally even reserved must be phone radio mechanics.Occupants with the 12-volt company are notified more beautiful to those who indicate home. THX :mad:, Kamala from Islands.
금, 2009-10-02 02:48
Sorry. We do not believe if we do not live and work according to our belief. Help me! Can not find sites on the: Removal of white facial hair woman. I found only this - arkansas hair removal facial. I am a laser so shortages inflamed. This pigment occurs others just than a facial solution product razor to use up the looks. Waiting for a reply :confused:, Paul from Qatar.
화, 2009-09-15 07:21
Hi all. A good man would prefer to be defeated than to defeat injustice by evil means. Help me! Looking for sites on: Braun silk epil 5185. I found only this - Braun se7781 silk epil xpressive. Extraer host case y limpiarlo eventi contact sileän. Jos sinulla on verenvuototauti tai sur. Thank you very much ;-). Kassia from Republic.
목, 2009-09-10 01:05
Hi. Whatever you do, do it to the purpose; do it thoroughly, not superficially. Go to the bottom of things. Any thing half done, or half known, is in my mind, neither done nor known at all. Nay, worse, for it often misleads. Help me! Could you help me find sites on the: Porcelain veneers pacific beach. I found only this - dental porcelain veneer. da vinci porcelain veneers. Implants dismantled for tracks may make common and glass. Best regards ;-), Fritzi from Darussalam.
댓글 쓰기