Ver Mensaje Individual
  #3 (permalink)  
Antiguo 18/07/2011, 10:35
Avatar de Italico76
Italico76
 
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Respuesta: Patron decorador

Cita:
Si te fijás en el diagrama uml del patrón (o sea la base), hay una realación de agregación, un decorador agrega componentes
en el constructor de tu clase Link no debes preguntar por el tipo de datos, ya que podés especificar qué tipo de datos debe aceptar el que es pasado por parámetro
Mejor asi ? sigo preguntando..pero porque quiero que LINK cree enlaces sobre strings sin necesidad de crear previamente un objeto compatible

Código PHP:
<?php
class html {
  protected 
$html;  
   
  function 
__construct($html){
    
$this->setHtml($html);
  }  
   
  function 
__tostring(){
    return 
$this->html;
  }
  
  function 
setHtml($html){
    
$this->html =$html;
  }
#

/* decorator */
abstract class tag extends html 
  protected 
$obj;
  
  function 
__construct (tag $obj=null){
    
$this->obj $obj;
  }   

#  
  
class link extends tag {
  private 
$uri;

  function 
__construct ($obj=null){
    if (!(
$obj instanceof tag)){
      if (!
is_object($obj)){
        
$obj = (string) $obj;
      }
    }  
    
$this->obj $obj;
      
  }  
  
  function 
setUri($uri){
    
$this->uri $uri;
  }

  function 
linkear (){
    
$this->setHtml ("<a href='{$this->uri}'>{$this->obj}</a>");
  }
  

  
 
class strong extends tag {

  function 
render(){
    
$this->setHtml ('<strong>'.$this->obj.'</strong>');
  }  
  
#

class italic extends tag {

  function 
render(){
    
$this->setHtml ('<i>'.$this->obj.'</i>');
  }  
  
#

class img extends html {
  private 
$img;
  
  function 
__construct($img){
    
$this->img $img;
    
$this->render();
  }  
  
  private function 
render(){
    
$this->setHtml ("<img src='{$this->img}' />");
  }
#


/* Creo imagen y le aplico enlace */
$i = new img ('http://2.bp.blogspot.com/-nURw-T8ErDM/ThYBg4eyhGI/AAAAAAAAB8I/Tapme43aapE/s72-c/google-picasa-blogger.jpg');
$i = new link($i);
$i->setUri('http://google.es');
$i->linkear();

/* Creo link sobre el HTML on_the_fly */
$h = new link('Google');
$h->setUri('http://google.es');
$h->linkear();

/* Le hago un strong */
$h = new strong ($h);
$h->render();

/* Le hago italica   */
$h = new italic ($h);
$h->render();

echo 
$i;
echo new 
html('<p/>');
echo 
$h;
__________________
Salu2!

Última edición por Italico76; 18/07/2011 a las 10:50