Интернет магазин китайских планшетных компьютеров |
|
Компьютеры - Прототип (шаблон проектирования) - Примеры30 марта 2011Оглавление: 1. Прототип (шаблон проектирования) 2. Примеры Пример C++
class Meal {
public:
virtual ~Meal;
virtual void eat = 0;
virtual Meal *clone const = 0;
//...
};
class Spaghetti : public Meal {
public:
Spaghetti;
void eat;
Spaghetti *clone const { return new Spaghetti; }
//...
};
Пример Java
/**
* Prototype Class
*/
public class Cookie implements Cloneable {
@Override
public Cookie clone throws CloneNotSupportedException {
// call Object.clone
Cookie copy = super.clone;
//In an actual implementation of this pattern you might now change references to
//the expensive to produce parts from the copies that are held inside the prototype.
return copy;
}
}
/**
* Concrete Prototypes to clone
*/
public class CoconutCookie extends Cookie { }
/**
* Client Class
*/
public class CookieMachine {
private Cookie cookie; // Could have been a private Cloneable cookie.
public CookieMachine {
this.cookie = cookie;
}
public Cookie makeCookie {
return this.cookie.clone;
}
public static void main {
Cookie tempCookie = null;
Cookie prot = new CoconutCookie;
CookieMachine cm = new CookieMachine;
for
tempCookie = cm.makeCookie;
}
}
Пример C#
using System;
namespace Prototype
{
class MainApp
{
static void Main
{
// Create two instances and clone each
Prototype p1 = new ConcretePrototype1;
Prototype c1 = p1.Clone;
Console.WriteLine ;
Prototype p2 = new ConcretePrototype2;
Prototype c2 = p2.Clone;
Console.WriteLine ;
// Wait for user
Console.Read;
}
}
// "Prototype"
abstract class Prototype
{
private string id;
// Constructor
public Prototype
{
this.id = id;
}
// Property
public string Id
{
get{ return id; }
}
public abstract Prototype Clone;
}
// "ConcretePrototype1"
class ConcretePrototype1 : Prototype
{
// Constructor
public ConcretePrototype1 : base
{
}
public override Prototype Clone
{
// Shallow copy
return this.MemberwiseClone;
}
}
// "ConcretePrototype2"
class ConcretePrototype2 : Prototype
{
// Constructor
public ConcretePrototype2 : base
{
}
public override Prototype Clone
{
// Shallow copy
return this.MemberwiseClone;
}
}
}
Пример PHP
<?php
/**
* Иерархия допустимых классов для создания прототипов
*/
abstract class Terrain {}
abstract class Sea extends Terrain {}
class EarthSea extends Sea {}
class MarsSea extends Sea {}
class VenusSea extends Sea {}
abstract class Plains extends Terrain {}
class EarthPlains extends Plains {}
class MarsPlains extends Plains {}
class VenusPlains extends Plains {}
abstract class Forest extends Terrain {}
class EarthForest extends Forest {}
class MarsForest extends Forest {}
class VenusForest extends Forest {}
/**
* Определение логики фабрики прототипов
*/
class TerrainFactory {
private $sea;
private $forest;
private $plains;
public function __construct {
$this->sea = $sea;
$this->plains = $plains;
$this->forest = $forest;
}
function getSea {
return clone $this->sea;
}
function getPlains {
return clone $this->plains;
}
function getForest {
return clone $this->forest;
}
}
/**
* Создание фабрики с заданными параметрами прототипа
*/
$prototypeFactory = new TerrainFactory(
new EarthSea,
new MarsPlains,
new VenusForest
);
/**
* Создание заданных объектов путём клонирования
*/
$sea = $prototypeFactory->getSea;
$plains = $prototypeFactory->getPlains;
$forest = $prototypeFactory->getForest;
Пример Ruby
module Prototype
# "Prototype"
class Prototype
# Property
# свойство id изначально присутствует у каждого объекта, поэтому воспользуемся свойством name
attr_reader :name
# Constructor
def initialize name
@name = name
end
end
end
# Create an instance and clone it
p1 = Prototype::Prototype.new "my name" # объект класса Prototype создается традиционны путем - методом new
p2 = p1.clone # метод clone существует у каждого объекта изначально - его не нужно определять
puts "p1.id = #{p1.id}, p2.id = #{p2.id}" # будут напечатаны разные id
puts "p1.name = #{p1.name}, p2.name = #{p2.name}" # будут напечатаны одинаковые name - "my name"
# Wait for user
gets
Пример VB.NET
Namespace Prototype
Class MainApp
Shared Sub Main
' Создание двух экземпляров и клонирование каждого
Dim p1 As Prototype = New ConcretePrototype1
Dim c1 As Prototype = p1.Clone
Console.WriteLine
Dim p2 As Prototype = New ConcretePrototype2
Dim c2 As Prototype = p2.Clone
Console.WriteLine
Console.Read
End Sub
End Class
' "Prototype"
MustInherit Class Prototype
Private m_id As String
' Конструктор
Public Sub New
Me.m_id = id
End Sub
' Свойство
Public ReadOnly Property Id As String
Get
Return m_id
End Get
End Property
Public MustOverride Function Clone As Prototype
End Class
' "ConcretePrototype1"
Class ConcretePrototype1
Inherits Prototype
' Конструктор
Public Sub New
MyBase.New
End Sub
Public Overrides Function Clone As Prototype
' Неполная копия
Return DirectCast, Prototype)
End Function
End Class
' "ConcretePrototype2"
Class ConcretePrototype2
Inherits Prototype
' Конструктор
Public Sub New
MyBase.New
End Sub
Public Overrides Function Clone As Prototype
' Неполная копия
Return DirectCast, Prototype)
End Function
End Class
End Namespace
Просмотров: 2564
|