Prototype Design Pattern

Prototype is a build design pattern that allows you to copy existing objects without making your code dependent on their classes.

Declare an abstract base class that specifies a pure virtual “clone” method, and maintain a dictionary of all concrete “cloneable” derived classes. Any class that needs a “polymorphic constructor” capability: It derives from the abstract base class, registers its prototypical instance, and implements the clone () operation.

So the client, instead of writing code that invokes the “new” operator on a wired class name, calls a “clone” operation on the abstract base class, supplying an enumerated string or data type that designates the class desired derivative.

Lets see PHP & C# code samples as below.

PHP

<?php

// I made a common prototype interface for cloning purpose.
// has a single function called _clone
abstract class Person {

    protected $name;

    abstract function __clone();

    function getName() {
        return $this->name;
    }
    function setName($name) {
        $this->name = $name;
    }
}

// Here is a concrete class extending the person prototype.
// we will implement the _clone method to support object cloning.
//This may contain a lot of fields and implementations but I will keep this simple for now.
class Boy extends Person {
    function __clone() {

    }
}


//here is our first time instantiation of boy concrete class
$person = new Boy();

//next time we will clone that object by using clone.
// we will also pass the name param dynamically.
// clone1
$person1 = clone $person;
$person1->setName('Hlaing');
$person1->getName();

// clone2
$person2 = clone $boy;
$person2->setName('Tin');
$person2->getName();

print_r($person1);
print_r($person2);
 
?>

C#

using System;
using System.Collections.Generic;

namespace HelloWorld
{
    // Here is my simple object that support object cloning.
    // I already build a function called copyclone to clone this object.
    public class Person
    {
        public string Name;

        public Person CopyClone()
        {
            return (Person)this.MemberwiseClone();
        }
    }

    
    class Program
    {
        static void Main(string[] args)
        {
            // firstly we build a object using new instantiation
            Person person = new Person();

            //next time we will clone that object by theh function copyclone.
            // we will also pass the name param dynamically.
            // clone1
            Person person1 = person.CopyClone();
            person1.Name = "Hlaing";

            // clone2
            Person person2 = person.CopyClone();
            person2.Name = "Tin";


            Console.WriteLine(person1.Name);
            Console.WriteLine(person2.Name);
        }   
    }
}

By Yuuma.



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム