16 Şubat 2015 Pazartesi

Fluent Interface

Fluent Interface
Fluent Interface ile amaç genellikle bir nesne üzerinde işlem yapmak. Amaç Builder gibi yeni bir nesne yaratmak değil!

Method Chaining Nedir?
Açıklaması şöyle. Yani hem Fluent Interface hem de Builder örüntüsü için Method Chaining kullanılır
Method chaining pattern has been around for years in Java and other languages. It is widely used to implement builders or fluent interfaces
Parent Chaining
Açıklaması şöyle. Yani Method Chaining ve dolayısıyla Fluent Interface ve Builder genellikle düz bir veri yapısı/nesne için kullanılır.
The issue is that, the chain termination determines the instance on which the next modifier method will apply on. For flat structures it is ok but for trees, navigation methods are necessary to go deeper or higher in the structure.
Daha hiyerarşik yapılar için şöyle yaparız
Html html = new Html()
  .head()
    ...
  .body()
    ...
    .div()
      ...;
İşin sırrı Html sınıfında head ve body sınıflarına kendisini parent olarak bildirmek. Şöyle yaparız
public class Html {

  private final Head head = new Head(this);

  private final TagNode<Html> body = TagNode.ofParent(this, "body");

  public Head head() {
    return head;
  }
    
  public TagNode<Html> body() {
    return body;
  }
}
Bu noktadan sonra yapılması gereken tek şey, child sınıflara parent nesneyi döndüren bir metod eklemek. Orijinal yazıda end() metodu yerine "__" diye bir alan kullanılmış ancak end() metodu çok daha okunaklı. Şöyle yaparız
public class Head {

  private final Html parent;  // For parent chaining

  public Html end() {
    return parent;
  }
  ...   
}

Fluent Interface ve İsimlendirme
Fluent Interface ile kullanılan metod isimleri İngilizceye gramerine benzemelidir.
Noun().Adjective().Verb().Adverb()
Mesela aşağıdaki kod parçasında noun + adjective + verb görülebilir.
Customers.WithInactiveAccount().Delete()
Fluent Interface ve C++
Fluent Interface ilk olarak Java ile kullanım bulmuş gibi gözükse de aslında C++ ile bu kullanım şekli çok önceden vardı. Özellikle stream sınıfları ile  kullanım şekli yaygındı. 

Örnek
Şöyle yaparız. Burada var olan ofstrema nesnesi üzerinde I/O işlemi yapılıyor
ofstream os;
os << "test" << 1 << endl;





Hiç yorum yok:

Yorum Gönder