名字: 原型模式(Prototype)
意图: 用原型实例指定创建对象的种类, 并且通过[b]拷贝[/b]这些原型创建新的对象.
动机: 替换较复杂的等级结构的工厂方法.
[img]http://dl.iteye.com/upload/attachment/195740/8e94461a-e53d-3430-bedd-96231df39674.jpg[/img]
意图: 用原型实例指定创建对象的种类, 并且通过[b]拷贝[/b]这些原型创建新的对象.
动机: 替换较复杂的等级结构的工厂方法.
class ScreenPrototype
attr_accessor :width, :height
def initialize(width, height)
self.width = width
self.height = height
end
def display(name)
puts "#{name} screen: #{self.width} x #{self.height}"
end
end
class Client
def self.run
h = {}
h[:normal] = ScreenPrototype.new(1024, 768)
h[:tft_lcd] = ScreenPrototype.new(1280, 800)
name = :normal
new = h[name].clone
new.display(name)
end
end
Client.run
[img]http://dl.iteye.com/upload/attachment/195740/8e94461a-e53d-3430-bedd-96231df39674.jpg[/img]
本文介绍了原型模式的基本概念及其在代码中的实现方式。通过使用原型模式,可以利用现有的实例作为原型来创建新的对象,这种方式减少了创建对象所需的步骤。文章还提供了一个具体的示例,展示了如何创建不同类型的屏幕对象。
804

被折叠的 条评论
为什么被折叠?



