Created
June 6, 2014 03:03
-
-
Save j201/7e2659ec29a4235ed993 to your computer and use it in GitHub Desktop.
Immutable OOP in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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)))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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