
//Target
protocol IText {
//Request()
func getText() -> String
}
//Adaptee
class StringList {
var rows: [String] = []
//SpecificRequest()
func getString() -> String {
return rows.joined(separator: "\n")
}
func add(_ value: String) {
rows.append(value)
}
}
//Adapter
class TextAdapter: StringList, IText {
//Request()
func getText() -> String {
return getString()
}
}
func getTextAdapter() -> TextAdapter {
let adapter = TextAdapter()
adapter.add("line 1")
adapter.add("line 2")
return adapter
}
//Client
let adapter = getTextAdapter()
let text = adapter.getText()
//text: line 1
// line 2
print("text is \"\(text)\"")
| Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. |