Archive for the ‘Design Patterns’ Category.
16 Temmuz 2010, 12:08
Factory method pattern factory objelerini implement eden desing pattern lardır. Elimizde class olmadan o class a ait objelerin oluşturulmasını sağlar.
UML :
Örnek :
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| abstract class Pizza {
public abstract int getPrice (); // count the cents
}
class HamAndMushroomPizza extends Pizza {
public int getPrice () {
return 850;
}
}
class DeluxePizza extends Pizza {
public int getPrice () {
return 1050;
}
}
class HawaiianPizza extends Pizza {
public int getPrice () {
return 1150;
}
}
class PizzaFactory {
public enum PizzaType {
HamMushroom,
Deluxe,
Hawaiian
}
public static Pizza createPizza (PizzaType pizzaType ) {
switch (pizzaType ) {
case HamMushroom :
return new HamAndMushroomPizza ();
case Deluxe :
return new DeluxePizza ();
case Hawaiian :
return new HawaiianPizza ();
}
throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
}
}
class PizzaLover {
/*
* Create all available pizzas and print their prices
*/
public static void main (String args []) {
for (PizzaFactory. PizzaType pizzaType : PizzaFactory. PizzaType. values()) {
System. out. println("Price of " + pizzaType + " is " + PizzaFactory. createPizza(pizzaType ). getPrice());
}
}
} |
Output:
Price of HamMushroom is 850
Price of Deluxe is 1050
Price of Hawaiian is 1150
Php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| <?php
abstract class Pizza
{
protected $_price;
public function getPrice ()
{
return $this->_price ;
}
}
class HamAndMushroomPizza extends Pizza
{
protected $_price = 8.5;
}
class DeluxePizza extends Pizza
{
protected $_price = 10.5;
}
class HawaiianPizza extends Pizza
{
protected $_price = 11.5;
}
class PizzaFactory
{
public static function createPizza ($type)
{
$baseClass = 'Pizza';
$targetClass = ucfirst($type).$baseClass;
if (class_exists($targetClass) && is_subclass_of($targetClass, $baseClass))
return new $targetClass;
else
throw new Exception ("The pizza type '$type' is not recognized.");
}
}
$pizzas = array('HamAndMushroom','Deluxe','Hawaiian');
foreach($pizzas as $p) {
printf(
"Price of %s is %01.2f".PHP_EOL ,
$p ,
PizzaFactory ::createPizza($p)->getPrice()
);
}
// Output:
// Price of HamAndMushroom is 8.50
// Price of Deluxe is 10.50
// Price of Hawaiian is 11.50
?> |
Kaynak: wikipedia
16 Temmuz 2010, 12:03
Object oriented programlama da factory objesi diğer objelerin oluşturulmasını sağlayan objedir. Constructor ların soyutlanmasıdır.
Genellikle her türden objeyi oluşturabilecek bir method ları vardır. Bu method ppsiyonel olarak objenin nasıl oluşturulacağıyla ilgili bir parametre kabul eder ve objeyi döner.
Kullanımı:
Factory objeleri daha çok frameworklerde ve kütüphanelerde kullanılır. Ayrıca test driven developmentta da kullanılır.
09 Temmuz 2010, 09:06
Kullanılan algoritma runtime de sürekli değişiyorsa strategy pattern kullanılması uygun olur. Algoritmalar bir interface ile encapsulate edilerek runtime da değiştirilebilir hale getirilir. Algoritmaları kullanan objenin bu değişiklerden haberi olmaz. Ayrıca başka bir algoritma interface i implement ederek kolayca sisteme eklebilir.
UML :

Java Örneği:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| //StrategyExample test application
class StrategyExample {
public static void main (String[] args ) {
Context context ;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd ());
int resultA = context. executeStrategy(3, 4);
context = new Context(new ConcreteStrategySubtract ());
int resultB = context. executeStrategy(3, 4);
context = new Context(new ConcreteStrategyMultiply ());
int resultC = context. executeStrategy(3, 4);
}
}
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
int execute (int a, int b );
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute (int a, int b ) {
System. out. println("Called ConcreteStrategyAdd's execute()");
return a + b ; // Do an addition with a and b
}
}
class ConcreteStrategySubtract implements Strategy {
public int execute (int a, int b ) {
System. out. println("Called ConcreteStrategySubtract's execute()");
return a - b ; // Do a subtraction with a and b
}
}
class ConcreteStrategyMultiply implements Strategy {
public int execute (int a, int b ) {
System. out. println("Called ConcreteStrategyMultiply's execute()");
return a * b ; // Do a multiplication with a and b
}
}
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
private Strategy strategy ;
// Constructor
public Context(Strategy strategy ) {
this. strategy = strategy ;
}
public int executeStrategy (int a, int b ) {
return strategy. execute(a, b );
}
} |
Php Örneği:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| <?php
class StrategyExample {
public function __construct() {
$context = new Context(new ConcreteStrategyA());
$context->execute();
$context = new Context(new ConcreteStrategyB());
$context->execute();
$context = new Context(new ConcreteStrategyC());
$context->execute();
}
}
interface IStrategy {
public function execute();
}
class ConcreteStrategyA implements IStrategy {
public function execute() {
echo "Called ConcreteStrategyA execute method\n";
}
}
class ConcreteStrategyB implements IStrategy {
public function execute() {
echo "Called ConcreteStrategyB execute method\n";
}
}
class ConcreteStrategyC implements IStrategy {
public function execute() {
echo "Called ConcreteStrategyC execute method\n";
}
}
class Context {
private $strategy;
public function __construct(IStrategy $strategy) {
$this->strategy = $strategy;
}
public function execute() {
$this->strategy->execute();
}
}
new StrategyExample();
?> |
Kaynak: wikipedia
08 Temmuz 2010, 09:12
Observer ları durum değiştiği zaman otomatik olarak uyarır.
Class Diagram:
Java Örnek:
Klavyeden girilen her satırı ayrı ayrı event olarak alır. java.util.Observer ve java.util.Observable classları kullanılmıştır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| /* File Name : EventSource.java */
package obs;
import java.util.Observable; //Observable is here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class EventSource extends Observable implements Runnable {
public void run () {
try {
final InputStreamReader isr = new InputStreamReader( System. in );
final BufferedReader br = new BufferedReader( isr );
while( true ) {
String response = br. readLine();
setChanged ();
notifyObservers ( response );
}
}
catch (IOException e ) {
e. printStackTrace();
}
}
} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| /* File Name: ResponseHandler.java */
package obs;
import java.util.Observable;
import java.util.Observer; /* this is Event Handler */
public class ResponseHandler implements Observer {
private String resp ;
public void update (Observable obj, Object arg ) {
if (arg instanceof String) {
resp = (String) arg ;
System. out. println("\nReceived Response: "+ resp );
}
}
} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| /* Filename : MyApp.java */
/* This is the main program */
package obs;
public class MyApp {
public static void main (String args []) {
System. out. println("Enter Text >");
// create an event source - reads from stdin
final EventSource evSrc = new EventSource ();
// create an observer
final ResponseHandler respHandler = new ResponseHandler();
// subscribe the observer to the event source
evSrc. addObserver( respHandler );
// starts the event thread
Thread thread = new Thread(evSrc );
thread. start();
}
} |
Kaynak: wikipedia
07 Temmuz 2010, 13:44
Object oriented programlamada kullanılan design pattern lardan biridir. Class library gibi büyük kodlar için basit arayüzler sunulmasını sağlar. Kütüphanenin kolay kullanılmasını ve anlaşılmasını sağlar. Kütüphaneyi kullanan kodların bağımlılılarını azaltır. Kod yazanlar için esneklik sağlar.
Yapısı:
Örnek:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| /* Complex parts */
class CPU {
public void freeze () { ... }
public void jump (long position ) { ... }
public void execute () { ... }
}
class Memory {
public void load (long position, byte[] data ) {
...
}
}
class HardDrive {
public byte[] read (long lba, int size ) {
...
}
}
/* Facade */
class Computer {
private CPU cpu =null;
private Memory memory =null;
private HardDrive hardDrive =null;
public Computer () {
this. cpu=new CPU ();
this. memory=new Memory ();
this. hardDrive=new HardDrive ();
}
public void startComputer () {
cpu. freeze();
memory. load(BOOT_ADDRESS, hardDrive. read(BOOT_SECTOR, SECTOR_SIZE ));
cpu. jump(BOOT_ADDRESS );
cpu. execute();
}
}
/* Client */
class You {
public static void main (String[] args ) {
Computer facade = new Computer ();
facade. startComputer();
}
} |
06 Temmuz 2010, 23:12
Bir objenin durumunu belirtmek için kullanılır. Objenin durumu runtime de sürekli değişiyorsa kullanılması uygun olur.
Örnek Java Implementasyonu:
State interface i ve iki implemantasyonu.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| interface State {
public void writeName (StateContext stateContext, String name );
}
class StateA implements State {
public void writeName (StateContext stateContext, String name ) {
System. out. println(name. toLowerCase());
stateContext. setState(new StateB ());
}
}
class StateB implements State {
private int count =0;
public void writeName (StateContext stateContext, String name ){
System. out. println(name. toUpperCase());
// change state after StateB's writeName() gets invoked twice
if(++count >1) {
stateContext. setState(new StateA ());
}
}
} |
StateContext class i state objelerini tutar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class StateContext {
private State myState ;
public StateContext () {
setState (new StateA ());
}
// normally only called by classes implementing the State interface
public void setState (State newState ) {
this. myState = newState ;
}
public void writeName (String name ) {
this. myState. writeName(this, name );
}
} |
Kullanımı
1 2 3 4 5 6 7 8 9 10 11
| public class TestClientState {
public static void main (String[] args ) {
StateContext sc = new StateContext ();
sc. writeName("Monday");
sc. writeName("Tuesday");
sc. writeName("Wednesday");
sc. writeName("Thursday");
sc. writeName("Saturday");
sc. writeName("Sunday");
}
} |
Output
monday
TUESDAY
WEDNESDAY
thursday
SATURDAY
SUNDAY
27 Nisan 2010, 19:08
Singleton design pattern bir class in sadece bir objesinin olmasını sağlar. Bu özellikle bir class in tek instance sinin bir çok obje tarafından kullanıldığı zaman işe yarar.
Singleton pattern Abstract Factory, Builder, Prototype, global değişkenleri için sıklıkla kullanılır.
Class diagramı
Java Implementation
1 2 3 4 5 6 7 8 9 10
| public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
} |