Skip to content

Instantly share code, notes, and snippets.

@j201
Created June 6, 2014 03:03
Show Gist options
  • Save j201/7e2659ec29a4235ed993 to your computer and use it in GitHub Desktop.
Save j201/7e2659ec29a4235ed993 to your computer and use it in GitHub Desktop.
Immutable OOP in Clojure
(defprotocol Shape
(perimeter [])
(draw [scene x y]))
(defrecord Square [s]
Shape
(perimeter []
(* s 4))
(draw [scene x y]
(draw-polygon scene
[x y]
[(+ x s) y]
[(+ x s) (+ y s)]
[x (+ y s)])))
(defrecord Circle [r]
Shape
(perimeter []
(* r 6.28))
(draw [scene x y]
(draw-circle scene r (+ x r) (+ y r))))
interface Shape {
public float perimeter();
public void draw(Scene scene, float x, float y);
}
class Square extends Shape {
float s;
public Square(float s) {
this.s = s;
}
public float perimeter() {
return s * 4;
}
public void draw(Scene scene, float x, float y) {
scene.startPolygon(x, y);
scene.moveTo(x + s, y);
scene.moveTo(x + s, y + s);
scene.moveTo(x, y + s);
scene.moveTo(x, y);
scene.endPolygon();
}
}
class Circle extends Shape {
float r;
public Circle(float r) {
this.r = r;
}
public float perimeter() {
return r * 6.28;
}
public void draw(Scene scene, float x, float y) {
scene.drawCircle(r, x + r, y + r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment