시스템에서 몇몇의 component 들이 한번 사용 될 수 있음
initializer call 은 비용이 많이 듬
추가적인 copy 를 방지하고 싶음
lazy instantiation 과 thread safety 케어할 필요가 있음
class SingletonDatabase
{
var captials = [String: Int]()
static var instanceCount = 0
// singleton
static let instance = SingletonDatabase()
private init()
{
type(of: self).instanceCount += 1
print("initializing database")
let path = "/Users/hong/capitals"
if let text = try? String(contentsOfFile: path, encoding: .utf8)
{
let string = text.components(separatedBy: .newlines)
.filter { !$0.isEmpty }
.map { $0.trimmingCharacters(in: .whitespaces) }
for i in 0..<string.count/2
{
captials[string[i*2]] = Int(string[i*2+1])!
}
}
}
func getPopulation(name: String) -> Int
{
return captials[name]!
}
}
func main()
{
let db = SingletonDatabase.instance
var city = "Seoul"
print("\(city) has population \(db.getPopulation(name: city))")
print(SingletonDatabase.instanceCount)
let db2 = SingletonDatabase.instance
city = "Tokyo"
print("\(city) has population \(db.getPopulation(name: city))")
print(SingletonDatabase.instanceCount)
}
class CEO : CustomStringConvertible
{
private static var _name = ""
private static var _age = 0
var name: String
{
get { return type(of: self)._name }
set(value) { type(of: self)._name = value }
}
var age : Int
{
get { return type(of: self)._age }
set(value) { type(of: self)._age = value }
}
public var description: String
{
return "\(name) is \(age) years old"
}
}
func main()
{
var ceo = CEO()
ceo.name = "Kang"
ceo.age = 88
var ceo2 = CEO()
ceo.age = 20
print(ceo)
print(ceo2)
}
안 좋은 방식 ... 비추천