Prototypeパターン

JavaScriptのprototypeではなくGoFのデサパタのPrototypeパターンです。Prototypeパターンは、クラスからインスタンスをつくるのではなく、あるインスタンスから別のインスタンスをつくるパターンのことをさす。

コードサンプル

PHPでは無理矢理感が否めないですけどPrototypeパターンのイメージです。(関心しない例です。Javaでやると長くなる...)

<?php

class Hoge
{
  var $class = null;

  function Hoge(){
    $this->class = 'Hoge';
  }
  function setClass($class){
    $this->class = $class;
  }
  function display(){
    print $this->class;
  }
  function clone(){
    return $this;
  }
}

$foo = new Hoge('hoge');
$foo->display(); // Hoge

$foo->setClass('Foo');
$foo_foo = $foo->clone();
$foo_foo->display(); // Foo
$foo_foo_foo = $foo_foo->clone();
$foo_foo_foo->display();

$foo->setClass('Bar');
$foo_bar = $foo->clone();
$foo_bar->display(); // Bar
$foo_foo->display(); // Foo

?>