comments ( 0 )
16 Temmuz 2010  posted by admin

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 :

 

factory

 

 

Ö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

comments ( 0 )
16 Temmuz 2010  posted by admin

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.

comments ( 0 )
09 Temmuz 2010  posted by admin

Capture2

comments ( 0 )
09 Temmuz 2010  posted by admin

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 : 

 

 

Capture

 

 

 

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

comments ( 0 )
08 Temmuz 2010  posted by admin

Observer ları durum değiştiği zaman otomatik olarak uyarır.

 

Class Diagram:

 

800px-Observer.svg

 

 

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

comments ( 0 )
07 Temmuz 2010  posted by admin

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ı:

 

FacadeDesignPattern

 

Ö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();
  }
}
comments ( 0 )
06 Temmuz 2010  posted by admin

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
comments ( 0 )
25 Haziran 2010  posted by admin

 1. Aşama

 

Netbeans de javafx desktop application oluşturuyoruz.

 

 

image

 

2. Aşama

Sol alttaki “Navigator” menüsünden aşağıdaki gibi jdbcdatasource ekliyoruz.

 

 

image

3. Aşama

Data Source Customizer menüsünden “Connection URL”, “username” ve “password” doldurup jdbcdatasource projemize ekliyoruz.

 

 

image

 

 

4. Aşama

Database de datasource denemek için basit bir tablo oluşturuyoruz.

 

 

image

 

 

4. Aşama

Database operasyonlarını yapacak class lar için bir paket oluşturuyoruz.

Oluşturduğumuz pakette database bağlantısını dönecek “DatabaseConnection.fx” class ını oluşturuyoruz.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * @author ugur
 */


public class DatabaseConnection {

    public function getConnention () : org.netbeans.javafx.datasrc.DbDataSource {
       
        var jdbcDataSource = org.netbeans.javafx.datasrc.DbDataSource {
            connectionString: "jdbc:mysql://www.ugurdonmez.com:3306/udonmez_proje"
            user: "username"
            password: "password"
            query: "select name from category"
        };
        return  jdbcDataSource;
    }
}

 

5. Aşama

Insert, Update ve Delete yapacak fonksiyonları “Category” isimli bir class oluşturup yazıyoruz.

 

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
/**
 * @author ugur
 */


public class Category {

    public function insertCategory(name : String ) {

        var pair = javafx.data.Pair {
            name: "name";
            value: name;
        }

        var pairs : javafx.data.Pair[];
        insert pair into pairs;

        var conn = DatabaseConnection{};
        conn.getConnention().create("category", pairs);
    }

    public function deleteCategory(id : Integer ) {

        var conn = DatabaseConnection{};
        var whereClause = "IDcategory = {id}";
        conn.getConnention().remove("category", whereClause);
    }

    public function updateCategory(id : Integer , name : String ) {

        var pair = javafx.data.Pair {
            name: "name";
            value: name;
        }

        var pairs : javafx.data.Pair[];

        insert pair into pairs;

        var whereClause = "IDcategory = {id}";
        var conn = DatabaseConnection{};

        conn.getConnention().update("category", pairs,whereClause);
    }
   
}

 

 

6. Aşama

Yazdığımız kodların çalışıp çalışmadığını test etmek için aşağıdaki kodu çalıştırıyoruz.

 

kod

1
2
3
4
var category = Category{};
category.insertCategory("New Categry");
category.deleteCategory(5);
category.updateCategory(4, "Updated Category");

 

önce

 

5

 

sonra

 

 

6

comments ( 0 )
05 Mayıs 2010  posted by admin
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
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author ugur
 */

public class SortListExample {

    public static void main(String args[]) {

        Integer[] intArray = new Integer[] {1,4,2,10,9,8,20,15,3,3,4};

        List<Integer> list = Arrays.asList(intArray);
       
        Collections.sort(list);

        for(Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println(" ");

        // reverse order
        Collections.sort(list,Collections.reverseOrder());

        for(Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println(" ");
    }
}

Output:
run:
1 2 3 3 4 4 8 9 10 15 20
20 15 10 9 8 4 4 3 3 2 1
BUILD SUCCESSFUL (total time: 0 seconds)

comments ( 0 )
30 Nisan 2010  posted by admin

Pager Tag kütüphanesi büyük verilerin jsp sayfası içinde sıralanması için kullanılan bir kütüphanedir. Google, Altavista, Yahoo gibi sitelerin indeks stillerini içerir. Dinamik sayfalar için çok kullanışlıdır.

 

Anasayfa

Demo

Download

 

Kurulumu

    1. WEB-INF/web.xml dosyasına aşağıdaki satırları ekleyin.
    <taglib>
      <taglib-uri>
    
    http://jsptags.com/tags/navigation/pager
    
      </taglib-uri>
      <taglib-location>
        /WEB-INF/jsp/pager-taglib.tld
      </taglib-location>
    </taglib>
               
              2. pager-taglib.tld dosyasını /WEB-INF/jsp altına kopyalayın.
                 
                3. pager-taglib.jar dosyasını /WEB-INF/lib altına kopyalayın.
                 

                Örnek Kullanımı

                 

                AltaVista Stili

                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
                <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>

                <pg:pager url="http://www.altavista.com/cgi-bin/query" maxIndexPages="20"
                             export="currentPageNumber=pageNumber">
                  <pg:param name="pg"/>
                  <pg:param name="q"/>

                <% for() { %>
                    <pg:item>
                      <%= data %>
                    </pg:item>

                <% } %>


                  <pg:index>
                    <font face=Helvetica size=-1>Result Pages:
                    <pg:prev>&nbsp;<a href="<%= pageUrl %>">[&lt;&lt; Prev]</a></pg:prev>
                    <pg:pages><%
                      if (pageNumber.intValue() < 10) {
                        %>&nbsp;<%
                      }
                      if (pageNumber == currentPageNumber) {
                        %><b><%= pageNumber %></b><%
                      } else {
                        %><a href="<%= pageUrl %>"><%= pageNumber %></a><%
                      }
                    %>
                    </pg:pages>
                    <pg:next>&nbsp;<a href="<%= pageUrl %>">[Next &gt;&gt;]</a></pg:next>
                    <br></font>
                  </pg:index>
                </pg:pager>