"The Grid. A digital frontier. I tried to picture clusters of information as they move through the computer. What did they look like? Ships? Motorcycles? Were the circuits like freeways? I kept dreaming of a world I thought I’d never see. And then, one day, I got in." — Tron: Legacy

2015-01-25

Java vs Clojure: Factory pattern

Java 

Shape interface: 

public interface Shape { 
public void draw(); 
} 


Concrete Shape implementations: 

 public class Circle implements Shape { 
@Override 
public void draw() { 
System.out.println("circle"); 
} 
} 

 public class Square implements Shape { 
@Override 
public void draw() { 
System.out.println("square"); 
} 
} 

 Shape Factory: 
 public class ShapeFactory { 
public Shape getShape(String shapeType){ 
if(shapeType.equals("circle")){ 
return new Circle(); 
} else if(shapeType.equals("square")){ 
return new Square(); 
} 
return null; 
} 
} 

 Usage: 

new ShapeFactory().getShape("circle").draw(); 
new ShapeFactory().getShape("square").draw(); 
  
Clojure 
  
Shape interface: 

(defprotocol Shape 
"Shape inteface" 
(draw [this])) 

 Concrete Shape implementations: 

(deftype Circle [] 
Shape 
(draw [this] "circle")) 
  
(deftype Square [] 
Shape 
(draw [this] "square")) 
  
Shape Factory: 

(defprotocol ShapesFactory 
"Shapes Factory" 
(getShape [this t])) 
  
(deftype ShapeFactory [] 
ShapesFactory 
(getShape [this t] (cond   (= t "circle") (Circle.) 
   (= t "square") (Square.)))) 
 Usage: 

(draw (getShape (ShapeFactory.) "circle")) 
(draw (getShape (ShapeFactory.) "square")) 
 

Brak komentarzy:

Prześlij komentarz