写点什么

架構師訓練營 week3 作業

用户头像
ilake
关注
发布于: 2020 年 10 月 04 日
  1. 请在草稿纸上手写一个单例模式的实现代码,拍照提交作业。





# eager load
class IdGenerator
@instance = IdGenerator.new
@@id = 0
private_class_method :new
def self.instance
@instance
end
def get_id
@@id += 1
end
def initialize
@@id = 0
end
end



# lazy load
class IdGenerator
@instance_mutex = Mutex.new
private_class_method :new
def self.instance
return @instance if @instance
@instance_mutex.synchronize do
@instance ||= new
end
@instance
end
def get_id
@@id += 1
end
def initialize
@@id = 0
end
end
  1. 请用组合设计模式编写程序,打印输出图 1 的窗口,窗口组件的树结构如图 2 所示,打印输出示例参考图 3。



# base_component.rb
class BaseComponent
attr_reader :name
def initialize(type, name)
@type = type
@name = name
end
def add
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
def remove
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
def print
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
end



# window_component.rb
class WindowComponent < BaseComponent
def initialize(name, type)
@name = name
@type = type
@sub_nodes = []
end
def add(component)
return unless component
@sub_nodes << component
end
def remove(component)
return unless component
@sub_nodes.delete(component)
@sub_nodes
end
def print
puts "#{@type} #{@name}\n"
@sub_nodes.each do |sub_node|
sub_node.print
end
end
end



# demo.rb
require './base_component.rb'
require './window_component.rb'
window_form = WindowComponent.new('window_form', 'window')
logo = WindowComponent.new('picture', 'logo')
login_button = WindowComponent.new('button', 'login')
register_button = WindowComponent.new('button', 'register')
frame = WindowComponent.new('frame', 'frame1')
user_name_label = WindowComponent.new('label', 'user_name')
user_name_box = WindowComponent.new('text_box', 'user_name_box')
password_label = WindowComponent.new('label', 'password')
password_box = WindowComponent.new('password_box', 'password_box')
remember_user_check_box = WindowComponent.new('check_box', 'remember_user_check_box')
remember_user_label = WindowComponent.new('label', 'remember_user')
forgot_password_link = WindowComponent.new('link_lable', 'forgot_password_link')
frame.add(user_name_label)
frame.add(user_name_box)
frame.add(password_label)
frame.add(password_box)
frame.add(remember_user_check_box)
frame.add(remember_user_label)
frame.add(forgot_password_link)
window_form.add(logo)
window_form.add(frame)
window_form.add(login_button)
window_form.add(register_button)
window.print



用户头像

ilake

关注

还未添加个人签名 2019.04.15 加入

还未添加个人简介

评论

发布
暂无评论
架構師訓練營 week3 作業