Geometric Shapes
class GraphicObject: CustomStringConvertible
{
var name: String = "Group"
var color: String = ""
var children = [GraphicObject]()
init() {}
init(name: String)
{
self.name = name
}
private func print(_ buffer: inout String, _ depth: Int)
{
buffer.append(String(repeating: "*", count: depth))
buffer.append(color.isEmpty ? "" : "\(color) ")
buffer.append("\(name)\n")
for child in children
{
child.print(&buffer, depth+1)
}
}
var description: String
{
var buffer = ""
print(&buffer, 0)
return buffer
}
}
class Square : GraphicObject
{
init(_ color: String)
{
super.init(name: "Square")
self.color = color
}
}
class Circle : GraphicObject
{
init(_ color: String)
{
super.init(name: "Circle")
self.color = color
}
}
func main()
{
let drawing = GraphicObject(name: "My Drawing")
drawing.children.append(Square("Red"))
drawing.children.append(Circle("Yellow"))
let group = GraphicObject()
group.children.append(Circle("Blue"))
group.children.append(Square("Blue"))
drawing.children.append(group)
print(drawing)
}
Neural Networks
class Neuron : Sequence
{
var inputs = [Neuron]()
var outputs = [Neuron]()
func makeIterator() -> IndexingIterator<Array<Neuron>>
{
return IndexingIterator(_elements: [self])
}
}
class NeuronLayer : Sequence
{
private var neurons: [Neuron]
func makeIterator() -> IndexingIterator<Array<Neuron>>
{
return IndexingIterator(_elements: neurons)
}
init(count: Int)
{
neurons = [Neuron](repeating: Neuron(), count: count)
}
}
extension Sequence
{
func connect<Seq: Sequence>(to other: Seq)
where Seq.Iterator.Element == Neuron,
Self.Iterator.Element == Neuron
{
for from in self
{
for t in other
{
from.outputs.append(t)
t.inputs.append(from)
}
}
}
}
func main()
{
var neuron1 = Neuron()
var neuron2 = Neuron()
var layer1 = NeuronLayer(count: 10)
var layer2 = NeuronLayer(count: 20)
neuron1.connect(to: neuron2)
neuron1.connect(to: layer1)
layer1.connect(to: neuron2)
layer1.connect(to: layer2)
}
정리
- 객체는 다른 객체를 상속이나/ 컴포지션을 통해서 사용할 수 있음
- 몇몇의 composed/ singular 객체들은 비슷하거나 다른 행동이 필요
- Composite 디자인 패턴은 우리들에게 두 객체의 타입을 동일하게 믿을 수 있게 함
- Swift 는 특별한 sequence 개념에 대해서 지원함