单例关闭修改开放扩展
Posted
技术标签:
【中文标题】单例关闭修改开放扩展【英文标题】:Singleton closed for modification open to extend 【发布时间】:2018-02-02 11:05:10 【问题描述】:我想知道如何做到这一点: 假设我有一个单例类
class Global
static let shared = Global()
private init()
我希望此类禁止修改。但开放扩展。
我想达到的结果
Global.shared.var1
当var1
来自另一个类时,会以某种方式扩展Global
。
这是一个愿望。甚至可能吗?实现这一目标的正确方法是什么。
【问题讨论】:
【参考方案1】:找到了一个暂时满足我目的的 hack(建议我更好的方法/替代方法):
class Students
static let shared = Students()
private init()
var name: [String] = ["Farhan","Hasan","Saba","Fatima"]
class Teachers
static let shared = Teachers()
private init()
var name: [String] = ["Mr. Riaz","Ms. Ayesha"]
//Base for Singleton, sort of proxy
class Global
private init()
//Somewhere else in your project
extension Global
static let students = Students.shared
//Somewhere else in your project
extension Global
static let teachers = Teachers.shared
//Apparently it served the purpose
print(Global.students.name) //prints: ["Farhan", "Hasan", "Saba", "Fatima"]
print(Global.teachers.name) //prints: ["Mr. Riaz", "Ms. Ayesha"]
【讨论】:
以上是关于单例关闭修改开放扩展的主要内容,如果未能解决你的问题,请参考以下文章