<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Umut Bayram on Medium]]></title>
        <description><![CDATA[Stories by Umut Bayram on Medium]]></description>
        <link>https://medium.com/@ubayram?source=rss-25a86af99fae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0tAWbEhgwC0oGuvq7Pqp5g.jpeg</url>
            <title>Stories by Umut Bayram on Medium</title>
            <link>https://medium.com/@ubayram?source=rss-25a86af99fae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:57:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ubayram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prototype Pattern — Java]]></title>
            <link>https://ubayram.medium.com/prototype-pattern-java-c62c426e4c0?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/c62c426e4c0</guid>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 14:27:28 GMT</pubDate>
            <atom:updated>2022-02-17T14:27:28.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prototype Pattern — Java</h3><blockquote>Prototype Pattern is in the creational design pattern group. Instead of generating a new object using the “new” keyword, object generation produces a new object by ‘clone’ it and editing new properties.</blockquote><p>Creating and valuing large objects with the new keyword can cause performance loss. In such a case, it may be advantageous to use a prototype design patten. By cloning the object, an object with the desired property will be created by simply changing the different value.</p><h3>Prototype Design Pattern Sample Application</h3><p>We create a BMW and Audi class that extends the Car abstract class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*FoCVc-4vXCxzFe69WiGsow.png" /><figcaption>Prototype Design Pattern Sample UML Diagram</figcaption></figure><pre>public abstract class Car implements Cloneable {<br>    protected String name;<br>    private Integer year;<br><br>    public abstract void printNameAndYear();<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    protected void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public Integer getYear() {<br>        return year;<br>    }<br><br>    public void setYear(Integer year) {<br>        this.year = year;<br>    }<br><br>    @Override<br>    public Object clone()   {<br>        Object clone = null;<br>        try<br>        {<br>            clone = super.clone();<br>        }<br>        catch (CloneNotSupportedException e)<br>        {<br>            e.printStackTrace();<br>        }<br>        return clone;<br>    }<br>}</pre><pre>public class Audi extends Car {<br><br>    public Audi() {<br>        this.setName(&quot;Audi&quot;);<br>        this.setYear(null);<br>    }<br><br>    @Override<br>    public void printNameAndYear() {<br>        System.<em>out</em>.println(&quot;Car : &quot; + this.getName() + &quot; Year : &quot; + getYear());<br>    }<br>}</pre><pre>public class Bmw extends Car {<br><br>    public Bmw() {<br>        this.setName(&quot;Bmw&quot;);<br>    }<br><br>    @Override<br>    public void printNameAndYear() {<br>        System.<em>out</em>.println(&quot;Car : &quot; + this.getName() + &quot; Year : &quot; + getYear());<br>    }<br>}</pre><p>From these classes, we create CarStore class instead of the new keyword, and the getCar() method in this class is returned by changing the properties of the previously created objects.</p><pre>public class CarStore {<br><br>    private static Map&lt;Class, Car&gt; <em>carMap </em>= new HashMap&lt;Class, Car&gt;();<br><br>    static {<br>        <em>carMap</em>.put(Audi.class, new Audi());<br>        <em>carMap</em>.put(Bmw.class , new Bmw());<br>    }<br><br>    public static Car getCar(Class clazz, Integer year) {<br>        Car car = (Car) <em>carMap</em>.get(clazz).clone();<br>        car.setYear(year);<br>        return car;<br>    }<br>}</pre><p><strong>Run test:</strong></p><pre>public class PrototypePattern {<br><br>    public static void main(String args[])  {<br>        Car car = CarStore.<em>getCar</em>(Audi.class,2015);<br>        car.printNameAndYear();<br><br>        car = CarStore.<em>getCar</em>(Bmw.class, 2017);<br>        car.printNameAndYear();<br>    }<br>}</pre><p><strong>Console output:</strong></p><pre>Car : Audi Year : 2015<br>Car : Bmw Year : 2017</pre><p><strong>Github:</strong></p><p><a href="https://github.com/u-bayram/prototype-pattern">https://github.com/u-bayram/prototype-pattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c62c426e4c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorator Design Pattern]]></title>
            <link>https://ubayram.medium.com/decorator-design-pattern-a55ab694e242?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a55ab694e242</guid>
            <category><![CDATA[decorator-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 14:03:46 GMT</pubDate>
            <atom:updated>2022-02-17T14:03:46.503Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>It is a design template used to add new properties to predefined classes without changing the structure.</blockquote><h3>Decorator Design Pattern Sample Application in Java</h3><p>Let’s add the Sunroof property to the BMW class that implements the Car interface with the decorator design pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*9hr-X_U9ApTrcrMa68m4DA.png" /><figcaption>Decorator Design Pattern Sample Uml Diagram</figcaption></figure><pre>public interface Car {</pre><pre>  void produce();<br>}</pre><pre>public class Bmw implements Car {<br>    @Override<br>    public void produce() {<br>        System.<em>out</em>.println(this.getClass().getName() + &quot; produce.&quot;);<br>    }<br>}</pre><p>To add the sunroof feature to the BMW class, we create a decorator abstract class that implements the Car interface.</p><pre>public abstract class BmwSunroofDecorator implements Car{<br>    private Car car = new Bmw();<br><br>    public Car getCar() {<br>        return car;<br>    }<br><br>    public void setCar(final Car car) {<br>        this.car = car;<br>    }<br>}</pre><p>By creating a BmwSunroof class that extends the BmwSunroofDecorator class, it completes the structure that runs the produce() method with the sunroof feature added.</p><pre>public class BmwSunroof extends BmwSunroofDecorator {<br>    @Override<br>    public void produce() {<br>        getCar().produce();<br>        addSunroof();<br>    }<br><br>    private void addSunroof() {<br>        System.<em>out</em>.println(this.getClass().getName() + &quot; adding.&quot;);<br>    }<br>}</pre><p><strong>Run test:</strong></p><pre>public class DecoratorTest {<br><br>    @Test<br>    public void test() {<br>        Car car = new BmwSunroof();<br>        car.produce();<br>    }<br>}</pre><p><strong>Console output :</strong></p><pre>pattern.decorator.sample.Bmw produce.<br>pattern.decorator.sample.BmwSunroof adding.</pre><p><strong>Github :</strong></p><p><a href="https://github.com/u-bayram/decorator-pattern">https://github.com/u-bayram/decorator-pattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55ab694e242" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Driven Architecture (EDA)]]></title>
            <link>https://ubayram.medium.com/event-driven-architecture-eda-c4a9516653a3?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4a9516653a3</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 10:35:17 GMT</pubDate>
            <atom:updated>2021-11-29T10:35:17.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drDMAs7BstZrCWTaqgG-1w.jpeg" /><figcaption>Event Driven Architecture — EDA</figcaption></figure><p>Event Driven Architecture (Olay Güdümlü Mimari — EDA), ayrıştırılmış, mikroservislere bölünmüş uygulamaların, bir olay yönetimi aracı ile (Message-Oriented-Middleware, Event-Broker) olayların asenkron olarak yayınlanabilen ve abone olunabilen bir yazılım tasarım modelidir.</p><p>Sürekli bir işlemi yapmak yerini, olay meydana geldikçe uygulamalar, mikroservisler ve bağlı cihazlar arasında gerçek zamanlı bilgi akışına izin veren kurumsal uygulamalar oluşturmanın yolunu sunar.</p><h4>Event Driven Architecture içerisinde ki “Event” nedir ?</h4><p>Bir sistem içerisinde her şey olaydır diyebiliriz. Bir e-ticaret sistemi içerisinde sipariş, fatura oluşturma, kargo bilgileri oluşturulması vb. tüm işlemler olaydır.</p><p>Event Driven Architecture, bir olay meydana geldiğinde, o olay ile ilgili bilgilerin ona ihtiyacı olan tüm sistemlere ve kişilere gönderilmesini sağlar. E-Ticaret sistemi içerisin sipariş oluşturulması olayı gerçekleştiğinde buna bağlı olarak Event Drivem Archictecture kargo bilgilerin oluşturulması, fatura bilgilerinin oluşturulması, ödeme bilgilerinin oluşturulması vb. işlemlerden sorumlu sistemlere bilgilerin ve olayın iletilmesini sağlamalıdır.</p><blockquote>Event-driven architecture 3 temel kavramı vardır.<br>1) Event producers: olay üreticileri<br>2) Event routers: olay yönlendiricileri <br>3) Event consumers: olay tüketicileri</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*pEKdOwQPb8kYcyhsvbVyZQ.jpeg" /><figcaption>Event-driven architecture</figcaption></figure><h4>Avantajları</h4><ol><li>Loose coupling</li></ol><p>Event Driven Architecture içerisinde bileşenler birbirine gevşek şekilde bağlanmıştır. Olayları üreten bileşenler ile tüketen bileşenler mantıksal olarak ayrılmıştır. Üreticiler (consumer) olayların nasıl tüketildiği ile ilgilenmezken, tüketiciler (producer) olayları üretmekle ilgilenmezler. Bu gevşek bağlantı nedeniyle, başka dillerde farklı bileşenler veya mikro hizmetler geliştirilebilir veya farklı teknolojiler kullanılabilir.Ayrıca uygulama ölçeklendirme de yardımcı olur. Üreticiler veya tüketiciler, diğer bileşenlerde herhangi bir mantıksal değişiklik yapılmadan gereksinimlere göre eklenebilir veya çıkarılabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rp3MhUN_4pesFis0nS9sfw.png" /><figcaption>Loose Coupling</figcaption></figure><p>2. Fault Tolerance</p><p>Üretici tarafından üretilen event, asenkrondur. Event işleyecek servis abone olur ve dinler. Eğer herhangi bir tüketici servis çöktüğünde, hata aldığında yada yokluğunda sistem çalışmaya devam edecektir. Böyle bir durumda event kuyrukta bekler. Tüketici servis çalışmaya başladığında event alınır ve işlenir.</p><p>Bir sipariş event i üretilim. Buna event’ abone olan 3 servis; fatura servisi, kargo servisi ve ödeme servisi bulunsun. Ödeme servisi ve kargo servisi bu event’ i işlesin, fakat fatura servisi çalışmadığı için işlemini tamamlayamasın. Bu durumda fatura servisi için event kuyrukta bekler, fatura servisi çalışmaya başladığında bu event işlenir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*DdtCzGKgihVmUQZGHIRNKQ.png" /><figcaption>Fault Tolerance</figcaption></figure><p>3. Cost-Effective :</p><p>Event Driven Architecture, üreticinin kuyruktaki mesaja basmasına ve tüketicinin mesajı almasına dayalı olarak çalışır. Bu şekilde, bir olayı kontrol etmek için sürekli yoklama gerekli değildir. Tüketilen CPU daha azdır ve ağ bant genişliği kullanımı azalır.</p><p>4. Scalability</p><p>Hizmetler birbirine bağlı olmadığından ölçeklendilebilinir. Servisler yoğunluğa göre yatay çoğaltılabilinir, ihtiyaca göre tüm servisler sürekli çalışır durumda olmak zorunda değildir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAK4T4yHUHrj1HfECbOHZQ.png" /><figcaption>Scalability</figcaption></figure><h4>Event Driven Achitecture Kavramları</h4><ol><li>Event Mesh</li></ol><p>Olayları takip eden ağ denilebilir. Event Driven Archictecture üretilen olaylar event-mesh üzerinde tutulur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*FWwmwaDJ2QbhnfdCjTSjJA.png" /></figure><p>2. Deferred Execution</p><p>Çevirisi ertelenmiş yürütme anlamına gelir. Mesajların asenkron işlenmesi, beklemesi ertelenmiş işlem yapmayı sağlar. REST tabanlı API’lere alışkınsanız, ertelenmiş yürütme kavramını anlamak zor olabilir. Event Driven Architecture özü, bir olay yayınladığınızda bir yanıt beklememenizdir. Olay komisyoncusu, bir süre sonra olabilecek tüm ilgili tüketiciler kabul edene kadar olayı tutar.</p><p>3. Eventual Consistency</p><p>Bir event sonrasında abone olan tüm tüketiciler, bu event’i işleme aldığını çalıştığını söyleyemeyiz, fakat bir servis kendi içerisinde abone olunan event’i aldığında kendi içerisinde tutarlı davranır.</p><p>4. Choreography</p><p>Deferred Execution ve Eventual Consistency kavramları bizi Choreography kavramına götürür. Standart microservis mimarisinde kullanılan orchestration yerine choreography ile olaylar event broker üzerinden koordine edilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_AFZvulWl5ZZYE1BG7hYQ.png" /><figcaption>Orchestration vs Choreography</figcaption></figure><p>5. CQRS — Command Query Responsibility Segregation</p><p>Temelinde Event Drive Architecture kullanılan CQRS, ana odağı write (yazma) ve read (okuma) sorumluluklarının ayrıştırılmasına dayanan bir mimari tasarım modelidir. CQRS mimarisi, CQS ilkesi baz alınarak kurulmuştur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*3XMw5OoaPMT3JMYgxlKHNg.png" /><figcaption>CQRS — Command Query Responsibility Segregation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4a9516653a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Pulsar — Apache Kafka vs Apache Pulsar]]></title>
            <link>https://ubayram.medium.com/apache-pulsar-apache-kafka-vs-apache-pulsar-418a998084d?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/418a998084d</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[apache-pulsar]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 07:20:19 GMT</pubDate>
            <atom:updated>2021-11-19T07:20:19.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Pulsar — Apache Kafka vs Apache Pulsar</h3><p>Apache Pulsar, Yahoo tarafından geliştirilen ve desteklenen, <strong>dağıtılmış mesajlaşma sistemi ve streaming</strong> sağlayan bir platformdur, <strong>Apache Software Foundation</strong> projeleri içerisinde yer alır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty5JCSAh3LTdkkRx1xt4Yw.png" /><figcaption>Apache Pulsar</figcaption></figure><p><strong>Linkedln </strong>tarafından tasarlanan<strong> Apache Kafka</strong> projesinin bir alternatifi sayılabilir. Kullanım amaçları benzer ama farklı teknoloji ve teknoloji altyapısı kullanan platformlardır. Apache Kafka streaming data processor , Apache Pulsar ise dağıtılmış mesajlaşma sistemi ve streaming oluşturur. <strong>Özünde ikisi benzer şeyleri farklı şekilde yapar.</strong></p><p>Pulsar ve Kafka uzun süredir yarışma halinde olan iki platformdur. Her ikisi de dünya çapında firmalar tarafından, çok büyük miktarda veriler üzerinde çalışan sistemlerde kullanılır ve tercih edilir.</p><p>Kafka, Pulsar’dan daha çok ve daha uzun süredir kullanılan platformdur. İki platformda açık kaynaklıdır. Pulsar, Kafka’ya göre daha yeni bir sistem olduğu için teknik olarak bazı noktalarda üstünlükleri bulunmaktadır. Örneğin <strong>Pulsar, veri akışını düzene sokan, çok daha hızlı ve verimli hale getiren yerleşik bir çoklu veri merkezi çoğaltma sistemine sahiptir.</strong></p><p>Apache Pulsar, büyük miktardaki veriyi Kafka’dan çok daha hızlı bir şekilde işlemek için idealdir. Bunun asıl nedeni Kafka’nın <strong>tek sistemli bir çözüm olarak oluşturulması ve tek katmanda</strong> çalışmasıdır. Pulsar ise tüm sürecin <strong>çok katmanlı </strong>bir sistemde akmasına izin verir.</p><p>Apache Pulsar’ı Apache Kafka’dan üstün kılan üç önemli özellik; <strong>çok kiracılı, coğrafi eşleme ve katmanlı depolama</strong>dır.</p><p>Pulsar <strong>horizontal scale</strong> edilebilen yapıya sahiptir. Birden çok coğrafi bölgedeki veri merkezleri arasında yapılandırılabilir, çoğaltma sağlanabilir.</p><p>Şuanda <a href="https://pulsar.apache.org/">resmi sitesinde</a> client olarak alttaki library ve örnekleri bulunmaktadır, ve programlama dillerinde geliştirmeyi desteklemektedir.</p><p>Java client<br>Go client<br>Python client<br>C++ client<br>Node.js client<br>WebSocket client<br>C# client</p><p><strong>İndirme Linki :</strong> <a href="https://pulsar.apache.org/docs/en/client-libraries/">https://pulsar.apache.org/docs/en/client-libraries/</a></p><p>Pulsar gecikme süresi ve dayanıklılık yanında veri erişimini garanti etmektedir. Özellikle &lt;5ms altında scale edilebilen dağıtım vaat etmektedir. Event Driven Architecture kullanılarak tasarlanmış bir mimaride bu sürenin ve dayanıklılığın ne kadar önemli olduğunu göz önünde bulundurursak önemli bir seçim ve kullanım kriteri olarak görebiliriz.</p><p><strong>Yahoo </strong>tarafından şuan bu yazı tarihi itibari ile 5 seneyi aşkın süredir aktif kullanılmaktadır.</p><p><a href="https://en.wikipedia.org/wiki/Multitenancy"><strong>Multitenancy </strong></a><strong>desteklemektedir. </strong>Bu yapıyı inşa edecek şekilde tasarlanmıştır. Isolation, kimlik doğrulama, yetkilendirme ve kotaları destekler.<strong> Kafka multitenancy desteklememektedir.</strong></p><p>Yönetim, araçlar ve izleme için <strong>REST Admin API</strong> si mevcuttur. Şuan için Bare metal, Kubernetes, Amazon Web Services(AWS) ve DataCenter Operating System(DC/OS) üzerinde devreye alınabilir ve destek sağlamaktadır.</p><p><a href="https://bookkeeper.apache.org/"><strong>Apache BookKeeper’a</strong></a><strong> dayalı kalıcı mesaj depolama kullanmaktadır.</strong> Yazma ve okuma işlemleri arasında IO düzeyinde izolasyon sağlamaktadır.</p><p><a href="http://pulsar.apache.org/docs/en/administration-pulsar-manager/">Arayüz üzerinden takip edilmek istenirse Pulsar Manager kurulabilir. Kuruluma ve kullanıma bu linkten ulaşabilirsiniz.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEb3m-dm1jLM8wuAKt1DDw.gif" /><figcaption>Pulsar Manager</figcaption></figure><h4>Apache Pulsar Kurulumu</h4><p>Docker üzerinde direk çalıştırabiliriz.</p><pre>docker run -it -p 6650:6650 -p 8080:8080 — mount source=pulsardata,target=/pulsar/data — mount source=pulsarconf,target=/pulsar/conf apachepulsar/pulsar:2.8.1 bin/pulsar standalone</pre><p>Bu komut ile çalıştırdığımızda pulsar servisi 6650, Pulsar Admin API 8080 portu üzerinde çalışacaktır.</p><h4>Pulsar Manager Kurulumu</h4><p>Pulsar Manager, Apache Pulsar üzerinde işlem ve izleme yapabileceğimiz bir arayüz sunar. Docker üzerinde çalıştırılabilir.</p><pre>docker pull apachepulsar/pulsar-manager:v0.2.0<br>docker run -it -p 9527:9527 -p 7750:7750 -e SPRING_CONFIGURATION_FILE=/pulsar-manager/pulsar-manager/application.properties apachepulsar/pulsar-manager:v0.2.0</pre><p><a href="http://localhost:9527/">http://localhost:9527</a> adresinden uygulama arayüzüne erişebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fbLMOddZsy_4EwXlSVxVA.png" /><figcaption>Pulsar Manager Login Page</figcaption></figure><p><a href="http://localhost:7750/">http://localhost:7750</a> adresinden Postman kullanarak kullanıcı ekleyebilirsiniz.</p><pre>CSRF_TOKEN=$(curl <a href="http://localhost:7750/pulsar-manager/csrf-token)">http://localhost:7750/pulsar-manager/csrf-token)</a></pre><p><a href="http://localhost:7750/pulsar-manager/csrf-token)">http://localhost:7750/pulsar-manager/csrf-token</a> get request yapılarak csrf token alınmalıdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAAPpgzVx1Ad0kxF-yFsdw.png" /><figcaption><a href="http://localhost:7750/pulsar-manager/csrf-token)">csrf-token</a> get request</figcaption></figure><pre> curl \ -H ‘X-XSRF-TOKEN: $CSRF_TOKEN’ \ -H ‘Cookie: XSRF-TOKEN=$CSRF_TOKEN;’ \ -H “Content-Type: application/json” \ -X PUT <a href="http://localhost:7750/pulsar-manager/users/superuser">http://localhost:7750/pulsar-manager/users/superuser</a> \ -d ‘{“name”: “admin”, “password”: “apachepulsar”, “description”: “test”, “email”: “username@test.org”}’</pre><p><a href="http://localhost:7750/pulsar-manager/users/superuser">http://localhost:7750/pulsar-manager/users/superuser</a> put request ile yeni kullanıcı bilgileri gönderilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYsQVjx8sKlnaJZwXFAeGw.png" /><figcaption><a href="http://localhost:7750/pulsar-manager/users/superuser">superuser</a> put request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9d4Y_tjzO5m1RSnM8EdLFg.png" /><figcaption><a href="http://localhost:7750/pulsar-manager/users/superuser">superuser</a> put request</figcaption></figure><h4>Apache Pulsar Java Client Sample</h4><p>Apache Pulsar için Java üzerinde Pulsar Client kütüphanesi kullanarak producer ve consumer servisleri bulunan bir örnek proje github adresinde bulunmaktadır.</p><pre>PulsarClient pulsarClient = PulsarClient.<em>builder</em>()<br>        .serviceUrl(&quot;pulsar://localhost:6650&quot;)<br>        .build();</pre><p>PulsarClient sınıfı ile connection sağlanır.</p><pre>Producer&lt;String&gt; stringProducer = pulsarClient.newProducer(Schema.<em>STRING</em>)<br>        .topic(&quot;my-topic&quot;)<br>        .create();<br><br>Thread producerThread = new Thread(new Runnable() {<br>    @Override<br>    public void run() {<br>        int index = 0;<br>        while (true) {<br>            try {<br>                String msg = &quot;Message &quot; + index;<br>                stringProducer.send(msg);<br>                System.<em>out</em>.println(&quot;Message sent : &quot; + msg);<br>                index++;<br>                Thread.<em>sleep</em>(1000);<br>            } catch (PulsarClientException e) {<br>                e.printStackTrace();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>});<br>producerThread.start();</pre><p>Thread içerisinde 1 saniyede mesaj gönderen producer komutları üstteki gibidir. Pulsar içerinde şemalar oluşturabiliyoruz. Bu producer sadece String bir değer göndermektedir.</p><pre>MessageListener messageListener = (consumer, msg) -&gt; {<br>    try {<br>        System.<em>out</em>.println(&quot;Message received: &quot; + new String(msg.getData()));<br>        consumer.acknowledge(msg);<br>    } catch (Exception e) {<br>        consumer.negativeAcknowledge(msg);<br>    }<br>};<br><br>Consumer consumer = pulsarClient.newConsumer()<br>        .topic(&quot;my-topic&quot;)<br>        .subscriptionName(&quot;my-subscription&quot;)<br>        .messageListener(messageListener)<br>        .subscribe();</pre><p>MessageListener ile consumer servisi oluşturulmuştur. “my-topic” üzerine gelen mesajlara subscribe olarak dinlenmektedir.</p><p>Uygulama çıktısı :</p><pre>Message sent : Message 0<br>Message received: Message 0<br>Message sent : Message 1<br>Message received: Message 1<br>Message sent : Message 2<br>Message received: Message 2<br>Message sent : Message 3<br>Message received: Message 3<br>Message sent : Message 4<br>Message received: Message 4<br>Message sent : Message 5<br>Message received: Message 5<br>Message sent : Message 6<br>Message received: Message 6<br>Message sent : Message 7<br>...</pre><p><strong>Github Link :</strong> <a href="https://github.com/u-bayram/apache-pulsar-sample">https://github.com/u-bayram/apache-pulsar-sample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=418a998084d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visitor Design Pattern in Java]]></title>
            <link>https://ubayram.medium.com/visitor-design-pattern-in-java-18da139b26d3?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/18da139b26d3</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[visitors]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 07:14:05 GMT</pubDate>
            <atom:updated>2021-11-19T07:14:05.667Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Visitor Design Pattern is behavioral design pattern that allows adding a new feature to classes in hierarchy without touching them.</blockquote><blockquote>Visitor design pattern is not suitable for situations where the main classes to be applied change a lot, it can cause problems.</blockquote><h4>Visitor Design Pattern Sample Application in Java</h4><p>We use the visitor pattern implementation to add the cruiseControl() capability to car classes that have drive() feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*BcsxlPd4X2bcux2nmw08sg.png" /><figcaption>Car Classes Uml Diagram</figcaption></figure><p>Additional features can be added via the CarVisitor interface. Here we just add the cruiseControl() property. It allows us to add this capability to the car classes to be added without touching these main classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*GRaU-uudb2kiGAqe6AwA6g.png" /><figcaption>CarVisitor Uml Diagram</figcaption></figure><p>We add accept() method to the Car classes so that they can use the feature in the CarVisitor class. This method takes the classes that implement the CarVisitor interface as input, and by running the visit() method of these classes, we reach the relevant capability.</p><pre>public interface Car {<br>    void drive();<br>    void accept(CarVisitor carVisitor);<br>}</pre><pre>public class BmwCar implements Car {<br>    @Override<br>    public void drive() {<br>        System.<em>out</em>.println(this.getClass().getName() + &quot; drive...&quot;);<br>    }<br><br>    @Override<br>    public void accept(CarVisitor carVisitor) {<br>        carVisitor.visit(this);<br>    }<br>}</pre><pre>public class VolkswagenCar implements Car {<br>    @Override<br>    public void drive() {<br>        System.<em>out</em>.println(this.getClass().getName() + &quot; drive...&quot;);<br>    }<br><br>    @Override<br>    public void accept(CarVisitor carVisitor) {<br>        carVisitor.visit(this);<br>    }<br>}</pre><p>We are creating the CarVisitor and CarCruiseControlVisitor classes to which we will add the Cruise Control feature. The cruise control feature is inside the visit() method.</p><pre>public interface CarVisitor {<br>    void visit(BmwCar bmwCar);<br>    void visit(VolkswagenCar volkswagenCar);<br>}</pre><pre>public class CarCruiseControlVisitor implements CarVisitor {<br>    @Override<br>    public void visit(BmwCar bmwCar) {<br>        System.<em>out</em>.println(bmwCar.getClass().getName() + &quot; add car cruise control.&quot;);<br>    }<br><br>    @Override<br>    public void visit(VolkswagenCar volkswagenCar) {<br>        System.<em>out</em>.println(volkswagenCar.getClass().getName() + &quot; dont add car cruise control.&quot;);<br>    }<br>}</pre><p>We inform you that this feature cannot be run for VolkswagenCar class, for BMWCar class, the feature is worked.</p><p>The main method where we will test visitor properties and car classes :</p><pre>public class VisitorPatternExample {<br><br>    public static void main(String[] args) {<br><br>        BmwCar bmwCar = new BmwCar();<br>        VolkswagenCar volkswagenCar = new VolkswagenCar();<br><br>        CarVisitor carVisitor = new CarCruiseControlVisitor();<br><br>        bmwCar.drive();<br>        volkswagenCar.drive();<br><br>        bmwCar.accept(carVisitor);<br>        volkswagenCar.accept(carVisitor);<br><br>    }<br>}</pre><p><strong>Console output :</strong></p><pre>com.example.visitor.car.BmwCar drive…<br>com.example.visitor.car.VolkswagenCar drive…<br>com.example.visitor.car.BmwCar add car cruise control.<br>com.example.visitor.car.VolkswagenCar dont add car cruise control.</pre><p><strong>Github :</strong></p><p><a href="https://github.com/u-bayram/visitor-pattern">https://github.com/u-bayram/visitor-pattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18da139b26d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tasarım Şablonları — Factory Pattern — Spring Boot Factory Bean & Abstract Factory Bean]]></title>
            <link>https://ubayram.medium.com/tasar%C4%B1m-%C5%9Fablonlar%C4%B1-factory-pattern-spring-boot-factory-bean-abstract-factory-bean-d2a157cea1dc?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2a157cea1dc</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 08:43:41 GMT</pubDate>
            <atom:updated>2021-06-11T08:43:41.441Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tasarım Şablonları — Factory Pattern — Spring Boot Factory Bean &amp; Abstract Factory Bean</h3><blockquote>Factory Pattern, creational design pattern grubunda yer alır. Verilen sınıf özelliklerinde nesne üretilip dönüş yapması sağlanır. Absract veya interface kullanılarak yapılabilinir. Spring Framework ve bir çok Framework alt yapısında kullanılmaktadır.</blockquote><p>Bir örnek üzerinden açıklayacak olursak; bir sistem içerisinde ortak özellikleri bulunan yazıcılar ile çalışma yapıldığında, ihtiyaca yönelik olarak nesne ve onun metotlarını kullanacak bir sistem tasarlayalım. Yazılım içerisini factory pattern ile tasarlayarak, ihtiyaç ve kullanıma yönelik olarak yazıcı nesnesini üretip dönmesini sağlayalım.</p><figure><img alt="Factory Pattern Sample Uml Diagram" src="https://cdn-images-1.medium.com/max/410/1*-p4rt1vO3zSNHuotXrwbVw.png" /><figcaption>Factory Pattern Sample Uml Diagram</figcaption></figure><p>Printer ortak özellikleri barındıran interface sınıfıdır. Printer özellikleri sağlayan Hp ve Xenop yazıcıları bulunmakta, Printer sınıfının özelliklerini implements etmektedir.</p><p>PrinterFactory sınıfı ise özellikleri tanımlanan yazını nesnesini üretip geri döndürmekten sorumludur. FactoryMethod içerisinde bu nesneleri üretip kullanacağız.</p><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public interface Printer {<br>    String getPrinterName();<br>}</pre><pre>public class Xenox implements Printer {<br>    public String getPrinterName() {<br>        return &quot;Xenox&quot;;<br>    }<br>}</pre><pre>public class Hp implements Printer {<br>    public String getPrinterName() {<br>        return &quot;Hp&quot;;<br>    }<br>}</pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public class PrinterFactory {<br><br>    public static Printer createPrinter(Class&lt;? extends Printer&gt; printer) {<br>        try {<br>            return printer.newInstance();<br>        } catch (Exception e) {<br>            throw new RuntimeException(&quot;Printer is not&quot;);<br>        }<br>    }<br>}</pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public class FactoryMethod {<br><br>    public static void main(String args[]) {<br>        List&lt;Printer&gt; printers = new ArrayList&lt;Printer&gt;();<br><br>        printers.add(PrinterFactory.<em>createPrinter</em>(Xenox.class));<br>        printers.add(PrinterFactory.<em>createPrinter</em>(Hp.class));<br>        printers.add(PrinterFactory.<em>createPrinter</em>(Xenox.class));<br>        printers.add(PrinterFactory.<em>createPrinter</em>(Hp.class));<br>        printers.add(PrinterFactory.<em>createPrinter</em>(Xenox.class));<br><br>        <em>showPrinters</em>(printers);<br>    }<br><br>    private static void showPrinters(List&lt;Printer&gt; printers) {<br>        printers.stream().forEach(printer -&gt; {<br>            System.<em>out</em>.println(printer.getPrinterName());<br>        });<br>    }<br>}</pre><p>PrinterFactory.createPrinter(&lt;PrinterClass&gt;) metotu ile istediğimiz yazıcı sınıfından nesne üretilmesini ve bu nesnenin içerisinde yazıcı adını getiren metot ile yazıcı adlarını yazdırdık.</p><h3>Factory Bean &amp; AbstractFactoryBean — Spring Boot</h3><p>Factory Bean, Spring Framework içerisin IoC Container üzerinden bean üretmemizi sağlar. Factory Pattern yapısını çok benzer, hatta spring framework içerisinde kullanımı diyebiliriz.</p><p>Factory Bean &amp; Abstract Factory Bean, Spring Framework içerisinde özellikle 3 amaç için kullanabiliriz :</p><ol><li>Datasource bean’leri üretirken,</li><li>Spring AOP kullanımına yönelik Proxy Bean kullanırken,</li><li>Hibernate Session Factory Bean üretirken</li></ol><p>Özellik konfigürasyon nesnelerinde kullanımı çok yaygındır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvxwshYDAL9qEBVe8t1-oA.png" /></figure><p>Student sınıfı ve bu sınıftan üretim yapacak StudentFactory ve StudentNonSingletonFactory sınıflarını oluşturalım.</p><pre><em>/**<br> * User: ubayram<br> * Date: 18.01.2021<br> * Time: 06:30<br> */<br></em>public class Student {<br>    private Long id;<br>    private String name;<br>    private String surname;<br><br>    public Student(Long id, String name, String surname) {<br>        this.id = id;<br>        this.name = name;<br>        this.surname = surname;<br>    }<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getSurname() {<br>        return surname;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Student{&quot; +<br>                &quot;id=&quot; + id +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, surname=&#39;&quot; + surname + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}<br></pre><pre><em>/**<br> * User: ubayram<br> * Date: 18.01.2021<br> * Time: 06:33<br> */<br></em>public class StudentFactory implements FactoryBean&lt;Student&gt; {<br><br>    private Long id;<br>    private String name;<br>    private String surname;<br><br>    @Override<br>    public Student getObject() throws Exception {<br>        return new Student(id, name, surname);<br>    }<br><br>    @Override<br>    public Class&lt;?&gt; getObjectType() {<br>        return Student.class;<br>    }<br><br>    @Override<br>    public boolean isSingleton() {<br>        return true;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br>}</pre><pre><em>/**<br> * User: ubayram<br> * Date: 18.01.2021<br> * Time: 07:27<br> */<br></em>public class StudentNonSingletonFactory extends AbstractFactoryBean&lt;Student&gt; {<br><br>    private Long id;<br>    private String name;<br>    private String surname;<br><br>    public StudentNonSingletonFactory() {<br>        setSingleton(false);<br>    }<br><br>    @Override<br>    public Class&lt;?&gt; getObjectType() {<br>        return Student.class;<br>    }<br><br>    @Override<br>    protected Student createInstance() throws Exception {<br>        return new Student(id, name, surname);<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }<br>}</pre><p>AbractFactoryBean abstract sınıfı FactoryBean interface’ini implements eden daha basit düzeyde konfigürasyon ve özellik girişi yaparak üretim yapmamızı sağlayan Spring Framework sınıfıdır. Basit düzeyde default değerlere sahiptir. Bu iki Spring Framework sınıfından FactoryBean üzerinde singleton, AbstractFactoryBean üzerinde ise protototype üretim sağlayacak factory sınıflarını oluşturduk.</p><pre><em>/**<br> * User: ubayram<br> * Date: 18.01.2021<br> * Time: 07:00<br> */<br></em>@Configuration<br>public class FactoryBeanAppConfig {<br><br>    @Bean(name = &quot;student&quot;)<br>    public StudentFactory studentFactory() {<br>        StudentFactory studentFactory = new StudentFactory();<br>        studentFactory.setId(1L);<br>        studentFactory.setName(&quot;Name&quot;);<br>        studentFactory.setSurname(&quot;Surname&quot;);<br>        return studentFactory;<br>    }<br><br>    @Bean<br>    public Student student() throws Exception {<br>        return studentFactory().getObject();<br>    }<br><br>    @Bean(name = &quot;studentNonSingleton&quot;)<br>    public StudentNonSingletonFactory StudentNonSingletonFactory() {<br>        StudentNonSingletonFactory studentFactory = new StudentNonSingletonFactory();<br>        studentFactory.setId(2L);<br>        studentFactory.setName(&quot;Name 2&quot;);<br>        studentFactory.setSurname(&quot;Surname 2&quot;);<br>        return studentFactory;<br>    }<br><br>    @Bean<br>    public Student studentNonSingleton() throws Exception {<br>        return studentFactory().getObject();<br>    }<br><br>}</pre><p>FactoryBeanAppConfig sınıfı üzerinde @ Configration anotasyonu kullanarak Spring Framework için konfigürasyon bean’ i oluşturuyoruz. Bu Bean içerisinde StudentNonSingletonFactory ve StudentFactory üzerinden üretilen Student nesnelerini kullanabileceğiz.</p><p>Factory sınıflarından Student nesneleri üretimi yapılması için @ Bean anotasyonu kullanıyoruz. Özellikleri Factory metotları içerisinde verebiliyoruz. Factory sınıfları içerisinde default değerler belirleyebilirdik.</p><pre><em>/**<br> * User: ubayram<br> * Date: 18.01.2021<br> * Time: 07:03<br> */<br></em>@RunWith(SpringJUnit4ClassRunner.class)<br>@ContextConfiguration(classes = FactoryBeanAppConfig.class)<br>public class FactoryBeanJavaConfigTest {<br><br>    @Autowired<br>    @Qualifier(&quot;student&quot;)<br>    private Student student;<br><br>    @Resource(name = &quot;&amp;student&quot;)<br>    private StudentFactory studentFactory;<br><br>    @Autowired<br>    @Qualifier(&quot;studentNonSingleton&quot;)<br>    private Student studentNonSingleton;<br><br>    @Resource(name = &quot;&amp;studentNonSingleton&quot;)<br>    private StudentNonSingletonFactory studentNonSingletonFactory;<br><br><br>    @Test<br>    public void testStudentFactory() {<br>        Assert.<em>assertEquals</em>(student.getId().toString(), String.<em>valueOf</em>(1L));<br>        Assert.<em>assertEquals</em>(student.getName(), &quot;Name&quot;);<br>        Assert.<em>assertEquals</em>(student.getSurname(), &quot;Surname&quot;);<br>    }<br><br>    @Test<br>    public void testStudentNonSingletonFactory() {<br>        Assert.<em>assertEquals</em>(studentNonSingleton.getId().toString(), String.<em>valueOf</em>(2L));<br>        Assert.<em>assertEquals</em>(studentNonSingleton.getName(), &quot;Name 2&quot;);<br>        Assert.<em>assertEquals</em>(studentNonSingleton.getSurname(), &quot;Surname 2&quot;);<br>    }<br><br>}</pre><p>JUnit Test Framework’ü ile ürettiğimiz nesneleri kontrol ediyoruz. Bu iki metot başarılı şekilde çalışacaktır.</p><p>@ Resource anotasyonu ile factory sınıflarından üretilen nesneleri student ve studentNonSingleton referanslarına inject ediyoruz.</p><p>@ ContextConfigration anotasoyonu ile Spring Framework konfigürasyon bean’ lerini gösteriyoruz.</p><p>Github Adresi : <a href="https://github.com/u-bayram/factory-method-pattern">https://github.com/u-bayram/factory-method-pattern</a></p><p>Teşekkürler.</p><p>End of file</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2a157cea1dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Scopes — Spring — Spring Boot]]></title>
            <link>https://ubayram.medium.com/spring-scopes-spring-spring-boot-ed4d5c1e35e7?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed4d5c1e35e7</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[prototype]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 13:05:40 GMT</pubDate>
            <atom:updated>2021-01-18T13:05:40.153Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Scopes — Spring — Spring Boot</h3><p>Java programlama dili içerisinde kurumsal uygulamalarda en çok kullanılan Spring Framework, nesneye yönelik programlamada sınıf ve nesne ilişkilerini temel alan ve yönetmemizi sağlayan bir framework’tür.</p><figure><img alt="Spring Framework" src="https://cdn-images-1.medium.com/max/1024/1*8R5B_LRuli6JjogWugLV9Q.png" /><figcaption>Spring Framework</figcaption></figure><p>Inversion of Control ve Dependency Injection ile nesnelerin oluşturulmasını ve kullanımını için temel alır. <a href="https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring">Bu kavramları bu linkten detaylı şekilde inceleyebilirsiniz.</a></p><blockquote>Spring Framework, sınıflarımız üzerinden manuel olarak kod içerisinde; nesne üretmemizi ve bu nesneleri yönetmemizi ortadan kaldırır. Uygulama içerisinde geliştirdiğimiz sınıflardan, hazır olarak kullanabilmemiz için<a href="https://en.wikipedia.org/wiki/JavaBeans#:~:text=In%20computing%20based%20on%20the,using%20getter%20and%20setter%20methods."> Java Bean üretir</a>. İlk geliştirme aşamalarında bean üreteceğimiz sınıflar için constructur olarak vereceğimiz özellikleri, bağımlılıkları, bağımlılıkların birbirine bağlanmasını ve hangi aşamada yeni bir bean oluşturulacağı gibi parametreleri XML üzerinden verirken, özellikle Spring Boot gibi Spring Framework üzerinde bir çatı görevi işlevi olan ve no xml configration prensibi ilke edinmiş framework ile birlikte neredeyse tam anlamıyla java anotasyonlar ile bu yönetim sağlanmaktadır.</blockquote><p>Spring scope ise hangi aşamada yeni bir bean oluşturulacağını yönetmemizi sağlar. Framework ilk geliştirme döneminden günümüze kadar eklenen yeni scope’lar ile <strong>birlikte 6 adet scope tipi bulunmaktadır.</strong></p><p><strong>singleton</strong> : Tek bir bean üretilir, her bir kullanımında bu bean inject edilir ve kullanılır, yeni bean oluşturulmaz. Default olarak tanımlanan scope tipidir.</p><p><strong>prototype :</strong> Her bir kullanımında yeni bir üretilip bean inject edilir ve kullanılır, kullanım sonrası finalize olur.</p><p><strong>request :</strong> Sadece web uygulamalarında kullanılır. Her request için yeni bir bean inject edilir.</p><p><strong>session : </strong>Sadece web uygulamalarında kullanılır. Her session için yeni bir bean inject edilir. Session değişene kadar bean finalize olmaz.</p><p><strong>application : </strong>Sadece web uygulamalarında kullanılır. Uygulama için global bir bean inject edilir.</p><p><strong>websocket :</strong> websocket teknolojisi için son eklenen scope tipidir. Açılan her websocket bağlantısı için bir bean üretilip inject edilir.</p><h3><strong>Singleton Scope</strong></h3><p>Default olarak tanımlı olan scope tipidir. Eğer bir scope tipi belirlenmez ise singleton olarak Spring Framework tarafından tanımlanır.</p><pre>@Scope(value = ConfigurableBeanFactory.<em>SCOPE_SINGLETON</em>)</pre><p>Sınıf üzerine eklenen @ Scope anotasyonu ile framework tarafından tanımlanması sağlanabilir.</p><p>StudentDao sınıfını ve bu sınıfı kullanan ClassService, SchoolService, StudentService sınıfları içerinde singleton scope olacak şekilde tanımlayalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88ac5067809a01917fa5db33a50ff851/href">https://medium.com/media/88ac5067809a01917fa5db33a50ff851/href</a></iframe><p>ClassService, SchoolService, StudentService sınıfları için bean üretilecek ve bu sınıflara StudentDao sınıfından üretilen tek bir bean inject edilecek aynı bean kullanılacaktır.</p><h3>Prototype Scope</h3><p>Prototype scope için ProductDao sınıfını ve bu sınıfı kullanan OrderService, ProductService sınıflarını tanımlayalım.</p><pre>@Scope(value = ConfigurableBeanFactory.<em>SCOPE_PROTOTYPE</em>)</pre><p>Sınıf üzerinde @ Scope anotasyonu ile ConfigurableBeanFactory.<em>SCOPE_PROTOTYPE </em>value değeri verilerek prototype scope tanımlanabilinir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69c34e43d4fc2c7e873dc19c62a30f4a/href">https://medium.com/media/69c34e43d4fc2c7e873dc19c62a30f4a/href</a></iframe><p>OrderService, ProductService sınıfları için bean üretilecek, her iki sınıf için ayrı bir ProductDao sınıfından üretilen bean inject edilecektir.</p><p>Singleton ve prototype scope için üretilen bean ‘ler JUnit Framework ile test edebiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbbb35d3722dc318572e15d870c19851/href">https://medium.com/media/bbbb35d3722dc318572e15d870c19851/href</a></iframe><p>singletonScopeTest() içerisinde singleton sample içerisinde tanımladığımız service sınıflarından çağıracağımız her bir StudentDao sınıfında ait bean aynı olmak zorundadır.</p><p>prototypeScopeTest() içerisinde default olarak singleton tanımlanan service sınıflarına inject edilen prototype scope tipi ile belirtilmiş ProductDao sınıfına ait bean’ler farklı olmak zorundadır.</p><figure><img alt="Singleton, Prototype Scopes Test Results" src="https://cdn-images-1.medium.com/max/390/1*NWWvhTGegQ6lcTU6OvHnWQ.png" /><figcaption>Singleton, Prototype Scopes Test Results</figcaption></figure><h3>Request Scope, Session Scope, Application Scope, Websocket Scope</h3><p>4 scope tipi sadece web uygulamalarında kullanacak şekilde tanımlanmıştır.</p><p>Request Scope, Session Scope, Application Scope için web isteklerine karşılık verecek web servisleri için SpringScopesRestController sınıfını ve sınıf içerisinde 3 farklı scope tipi ile tanımlı sınıfları kullanan metotları tanımlayalım. DataApplicationScopeService, DataRequestScopeService, DataSessionScopeService sınıfları 3 farklı scope tipi tanımlı ve SpringScopesRestController sınıfı için bean üretilip inject edilir.</p><p>ApplicationScope, sınıf üzerinde @ ApplicationScope anotasyonu ile tanımlanır.</p><p>SessionScope, sınıf üzerinde @ SessionScope anotasyonu ile tanımlanır.</p><p>RequestScope, sınıf üzerinde @ RequestScope anotasyonu ile tanımlanır.</p><p>WebSocket Scope için bir anotasyon tanımı bulunmamaktadır. WebSocket açılan bağlantıda kullanılan bean tanımlamaları WebSocket scope özellikleriyle çalışır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/878f7768d6c2af14c5ba333b0183140d/href">https://medium.com/media/878f7768d6c2af14c5ba333b0183140d/href</a></iframe><p>Request Scope için hazırlanan servis içinde bulunan, request scope tipi belirlenen sınıfın içerisinde ki count değeri her request’te bir değer artırılarak kaydediliyor. Fakat her request’te count değeri bean yeniden üretileceği için aynı kalacaktır. Request <a href="http://localhost:9090/application">http://localhost:9090/requestScopeSample</a> adresi üzerinden yapılmaktadır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd447ccdeaa7753d23ae718ce6fcb67e/href">https://medium.com/media/cd447ccdeaa7753d23ae718ce6fcb67e/href</a></iframe><p>JUnit ile yazılan web integration test üzerinden requestScope için hazırlanan servise iki farklı request atılıyor. Atılan değerlerin count değeri artmadığı için aynı olması gerekiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*hqE-68rMqdF5LZQJ-jcQfg.png" /><figcaption>Request Scope Test Result</figcaption></figure><p>Test sonuçları başarılı bir şekilde görülecektir. Atılan iki farklı request için ayrı bean’ler oluşacak default count değerine sahip olacaktır. Response bu nedenle aynı olacaktır.</p><p>Session scope içerisinden atılan requestleri aynı browser üzerinde aynı session olacağı için artmasını göreceğiz. Fakat gizli bir pencerede açtığımızda yeni bir session üretileceği için yeni bir bean üretilecek count değer başlangıç değeri olacaktır. Her gelen request için session scope tanımlanan bean içerisindeki counter değeri bir değer artırılacaktır. Request <a href="http://localhost:9090/application">http://localhost:9090/sessionScopeSample</a> adresi üzerinden yapılacaktır.</p><figure><img alt="Session Scope Değer Artışı" src="https://cdn-images-1.medium.com/max/426/1*vmP-rFDH7Jj4o97Xcslh2g.png" /><figcaption>Session Scope Değer Artışı</figcaption></figure><figure><img alt="Session Scope Gizli Sayfa Değer Artışı" src="https://cdn-images-1.medium.com/max/559/1*nO1seLqXstq7IGip8_b07g.png" /><figcaption>Session Scope Gizli Sayfa Değer Artışı</figcaption></figure><p>Ekran görüntülerinde göründüğü gibi gizli sayfada session yeniden üretildiği için başlangıç değerinden itibaren counter artış göstermiştir.</p><p>Application scope içerisinden atılan requestler uygulama çalıştığı sürece session ve request farketmeksizin counter değerinin artmasını göreceğiz. Uygulama açık kaldığı sürece tek bir bean üretilecek ve counter değeri bu değer üzerinde saklanacaktır. Her request geldiğinde counter değeri bir değer artacaktır. Request <a href="http://localhost:9090/application">http://localhost:9090/applicationScopeSample</a> adresi üzerinden yapılacaktır.</p><figure><img alt="Application Scope Değer Artışı" src="https://cdn-images-1.medium.com/max/446/1*6-oQz1ELnS5a7zjOvJF2lg.png" /><figcaption>Application Scope Değer Artışı</figcaption></figure><figure><img alt="Application Scope Gizli Sayfa Değer Artışı" src="https://cdn-images-1.medium.com/max/429/1*nWYWEL9t6a3inmXKcpKP3g.png" /><figcaption>Application Scope Gizli Sayfa Değer Artışı</figcaption></figure><p>Ekran görüntülerinde göründüğü gibi farklı bir request, farklı bir session olması bean üretmeyeceği, aynı bean inject edilip değeri artırıldığı için değer artışı gözlenmektedir. Uygulama çalışma süresince application scope olarak tanımlanan tek bir bean inject edilip çalışacaktır.</p><p>Github Adresi : <a href="https://github.com/u-bayram/spring-scopes">https://github.com/u-bayram/spring-scopes</a></p><p>Teşekkürler.</p><p>End of file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed4d5c1e35e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tasarım Şablonları — Builder Pattern & Fluent Builder Pattern— Java — Lombok]]></title>
            <link>https://ubayram.medium.com/tasar%C4%B1m-%C5%9Fablonlar%C4%B1-builder-pattern-fluent-builder-pattern-java-lombok-41415c3e8b0a?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/41415c3e8b0a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[pojo]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 08:35:19 GMT</pubDate>
            <atom:updated>2021-01-14T08:35:19.615Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tasarım Şablonları — Builder Pattern &amp; Fluent Builder Pattern— Java — Lombok</h3><blockquote>Builder Pattern özellikle aynı sınıf üzerinde farklı değişken sayıları ile constructor üzerinden nesne oluşturma ihtiyacı bulunduğu durumlarda constructor’ın kompleks yapısını ve kod tekrarını engellemek, düzenlemek için kullanılmaktadır. Özellikle büyük projelerde Pojo sınıflara eklenen yeni değişken (özellik) kullanıldığı tüm yerlerde düzenleme gerektirmesi nedeniyle kontrolü zor hale getirmektedir. Builder Pattern ile bu daha esnek ve okunması kolay hale gelmektedir.</blockquote><p>Builder pattern bir creational design pattern grubunda yer alır.</p><p>Builder Pattern için bir örnek üzerinde incelemek daha yararlı olacaktır. Bu nedenle, özellikleri tanımlanan bir araba sipariş etmeyi sağlayan bir order yapısı üzerinde duracağız.</p><figure><img alt="Ordered Car in Builder Pattern UML Diagram" src="https://cdn-images-1.medium.com/max/675/1*M_Z5cO-kqKfaf69EO1xt1g.png" /><figcaption>Ordered Car in Builder Pattern &amp; Fluent Pattern UML Diagram</figcaption></figure><p>3 adet Pojo sınıfımız bulunmaktadır. (<a href="https://www.geeksforgeeks.org/pojo-vs-java-beans">Pojo sınıflarının ne olduğu bu linkten inceleyebilirsiniz.</a>) Model ve Company nesneleri Car pojo nesnesin bir özelliği olarak kullanılmaktadır.</p><pre>Model.java<br><br><em>/**<br> * @author umut.bayram<br> */<br></em>public class Model {<br>    private String name;<br><br>    public Model(String name) {<br>        this.name = name;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><pre>Company.java<br><br><em>/**<br> * @author umut.bayram<br> */<br></em>public class Company {<br>    private String name;<br><br>    public Company(String name) {<br>        this.name = name;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><pre>Car.java</pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public class Car {<br>    private Company company;<br>    private Model model;<br><br>    public Company getCompany() {<br>        return company;<br>    }<br><br>    public void setCompany(Company company) {<br>        this.company = company;<br>    }<br><br>    public Model getModel() {<br>        return model;<br>    }<br><br>    public void setModel(Model model) {<br>        this.model = model;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Car{&quot; +<br>                &quot;company=&quot; + company.getName() +<br>                &quot;, model=&quot; + model.getName() +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>Builder Pattern ve Fluent Builder Pattern ortak olarak bu 3 Pojo sınıfında işlem yapacak şekilde tasarlanmıştır. Proje ihtiyacı veya tercihe göre 2 yöntemden birisi tercih edebilirsiniz.</p><h3>Fluent Builder Pattern</h3><pre><em>OrderFluentBuilder.java</em></pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public class OrderFluentBuilder {<br>    private Company company;<br>    private Model model;<br><br>    private OrderFluentBuilder() {<br><br>    }<br><br>    public static OrderFluentBuilder startBuild() {<br>        return new OrderFluentBuilder();<br>    }<br><br>    public OrderFluentBuilder withCompany(Company company) {<br>        this.company = company;<br>        return this;<br>    }<br><br>    public OrderFluentBuilder withModel(Model model) {<br>        this.model = model;<br>        return this;<br>    }<br><br>    public Car build() {<br>        Car car = new Car();<br>        car.setCompany(this.company);<br>        car.setModel(this.model);<br>        return car;<br>    }<br><br>}</pre><p>Builder sınıfımız constructor private olacak ve sadece static olan startBuild() metotu ile kullanılacak şekilde tanımlanır. Sınıf içerisinde bulunan diğer her bir metot ise Car nesnesinin özelliklerini alarak üretecek şekilde tanımlanır. build() metodu en son özellikleri verilen Car nesnesini üretip geri dönüşünü yapacaktır.</p><p>Fluent Builder Pattern bu şekilde tamamlanır. Aşağıdaki kod blokunda olduğu gibi uygulama içerisinde OrderFluentBuilder sınıfı üzerinden Car sınıfına ait nesneler üretilip kullanılabilinir.</p><pre>Car car = OrderFluentBuilder.<em>startBuild</em>().withCompany(new Company(&quot;Bmw&quot;)).withModel(new Model(&quot;116d&quot;)).build();<br>System.<em>out</em>.println(car.toString());<br><br>car = OrderFluentBuilder.<em>startBuild</em>().withCompany(new Company(&quot;Wolswagen&quot;)).withModel(new Model(&quot;Polo&quot;)).build();<br>System.<em>out</em>.println(car.toString());</pre><h3><strong>Builder Pattern</strong></h3><p>Builder Pattern için nesne üretimini ve özelliklerini tanımlayan OrderManager, OrderBuilder, BmwOrderBuilder ve WolswagenOrderBuilder sınıflarını kullanacağız.</p><pre><em>OrderBuilder.java</em></pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public abstract class OrderBuilder {<br><br>    private Car car;<br><br>    public OrderBuilder() {<br>    }<br><br>    public Car getCar() {<br>        if (this.car == null)<br>            this.car = new Car();<br>        return this.car;<br>    }<br><br>    public abstract void setModel(Model model);<br><br>    public abstract void setCompany(Company company);<br>}</pre><p>OrderBuilder absract sınıfı ortak özellikleri barındıran ve ortak olarak üretilecek olan nesneleri referans edecek sınıftır.</p><pre>BmwOrderBuilder.java</pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public class BmwOrderBuilder extends OrderBuilder {<br>    public void setModel(Model model) {<br>        getCar().setModel(model);<br>    }<br><br>    public void setCompany(Company company) {<br>        getCar().setCompany(company);<br>    }<br>}</pre><pre>WolswagenOrderBuilder.java</pre><pre><em>/**<br> * @author umut.bayram<br> */<br></em>public class WolswagenOrderBuilder extends OrderBuilder {<br>    public void setModel(Model model) {<br>        getCar().setModel(model);<br>    }<br><br>    public void setCompany(Company company) {<br>        getCar().setCompany(company);<br>    }<br>}</pre><p>WolswagenOrderBuilder, BmwOrderBuilder özelliklere göre Car nesnesi üretecek olan, OrderBuilder sınıfını extend eden sınırlardır.</p><pre><em>OrderManager.java<br>/**<br> * @author umut.bayram<br> */<br></em>public class OrderManager {<br>    private OrderBuilder orderBuilder;<br><br>    public Car createOrder(String company, String model) {<br>        if (company.equals(&quot;Bmw&quot;)) {<br>            orderBuilder = new BmwOrderBuilder();<br>        } else if (company.equals(&quot;Wolswagen&quot;)) {<br>            orderBuilder = new WolswagenOrderBuilder();<br>        } else {<br>            throw new RuntimeException(&quot;Car company is not found&quot;);<br>        }<br>        orderBuilder.setCompany(new Company(company));<br>        orderBuilder.setModel(new Model(model));<br>        return orderBuilder.getCar();<br>    }<br><br>    public void printOrder() {<br>        System.<em>out</em>.println(orderBuilder.getCar().toString());<br>    }<br>}</pre><p>OrderManager sınıfı gelen özelliklere göre Car sınıfına ait nesneyi üretecektir. Burada dikkat edilmesi gereken aslında WolswagenOrderBuilder, BmwOrderBuilder sınıflarını kullanmadan OrderBuilder sınıfı üzerinden bu işlemleri yapabilirdik, fakat bu noktada daha nesne özelliklerine göre daha özelleştirilmiş bir yapı kurulmasını sağladık. Uygulama içerisinde kullanımını aşağıdaki kod bloğunda görebilirsiniz.</p><pre>OrderManager orderManager = new OrderManager();<br>orderManager.createOrder(&quot;Wolswagen&quot;, &quot;Polo&quot;);<br>orderManager.printOrder();<br><br>orderManager = new OrderManager();<br>orderManager.createOrder(&quot;Bmw&quot;, &quot;116d&quot;);<br>orderManager.printOrder();</pre><h3>Lombok &amp; Fluent Builder Pattern</h3><p>Lombok kütüphanesi ile Fluent Builder Pattern sınıfı otamatik generate ederek kurulabilirsiniz.</p><p>Lombok tarafından üretilecek Builder Pattern metotlar ve sınıfının oluşması için Pojo sınıf üstünde @ Builder anotasyonu kullanmak yeterlidir. (@ ToString anotasyonu Pojo nesnenin toString() metodunu generate etmek için kullanılır.)</p><pre>@Builder<br>@ToString<br>public class Student {<br>    private Long id;<br>    private String name;<br>    private String surname;<br>    private Integer age;<br>}</pre><p>Üretilen builder özelliklerini kullanımını aşağıdaki kod blokunda inceleyebilirsiniz.</p><pre>Student student = Student.<em>builder</em>().id(1L).name(&quot;Ali&quot;).surname(&quot;Bak&quot;).age(12).build();<br>System.<em>out</em>.println(student.toString());</pre><p>Github Adresi : <a href="https://github.com/u-bayram/builder-pattern">https://github.com/u-bayram/builder-pattern</a></p><p>Teşekkürler.</p><p>End Of File</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41415c3e8b0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tasarım Şablonları — Singleton Pattern — Java]]></title>
            <link>https://ubayram.medium.com/tasar%C4%B1m-%C5%9Fablonlar%C4%B1-singleton-pattern-java-aa23adacd32d?source=rss-25a86af99fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa23adacd32d</guid>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[eager]]></category>
            <category><![CDATA[lazy]]></category>
            <category><![CDATA[desing-pattern]]></category>
            <dc:creator><![CDATA[Umut Bayram]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 11:20:15 GMT</pubDate>
            <atom:updated>2021-01-12T11:24:07.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tasarım Şablonları — Singleton Pattern — Java</h3><blockquote>Tasarım şablonları hakkında bir çok yazı ve materyal bulunmasına rağmen özellikle gelişen programlama dilleri ve framework’ler içerisinde kendisini geliştirmekte kullanımlarında ufak değişiklikler oluşturmaktır. Bu yazıda Singleton Pattern için Java (minimum JDK 1.8) programlama dili içerisinde ki güncel kullanımlarını farklı yapılarda ele alacağız.</blockquote><blockquote>Ayrıca bu yöntemleri sample olarak github adresimde paylaşacağım.</blockquote><p>Nesneye yönelik programlama içerisinde; projelerin, ekiplerin büyümesi ve yaklaşımın gelişmesi ile birlikte nesne oluşturma soyutlama yöntemleri gelişmiş büyük önem kazanmıştır. Bununla birlikte evrensel kullanım yöntemleri ortaya çıkmış ve adı tasarım şablonları olarak anılmaktadır.</p><p>Singleton pattern, <strong>Creational Design Pattern </strong>grubunda yer alır. Birden çok sınıfın aynı instance içerisinde bir sınıf için üretilecek olan tek bir nesneyi kullanması sağlanır. Bir çok framework (Spring Services, Contollers, Repositories) nesne üretme yöntemi olarak bu tasarım şablonunu kullanmaktadır. (Spring Framework üzerinde bulunan scope tipleri arasında singleton yer almakta, default olarak tanımlanmıştır. Spring Framework sınıflar üzerinde tanımlanan scope tipi, nesne üretimin nasıl olacağını belirleyeceğimizi sağlayan parametredir.)</p><p>Nesne üretim aşamasında memory üzerine üretim ve yüklenme durumları, thread safe olarak çalışması konusunda farklılıklar oluşmaktadır. Bu konuda uygulamanın ihtiyacına göre ve genel olarak yazılım içerisinde ki kod farklılıkları sağlanmaması adına bir yöntem belirlenebilir.</p><p><em>Java programlama dili içerisinde benim araştırmalarıma göre, ihtiyaca yönelik en çok tercih edilen kullanım yöntemleri :</em></p><ol><li><em>Eager Initilization</em></li><li><em>Static Block Initialization</em></li><li><em>Lazy Initialization</em></li><li><em>Lazy Initialization Optimization</em></li><li><em>Using By Enum</em></li></ol><p>Bu yöntemleri teker teker inceleyelim.</p><h3>1. Eager Initialization</h3><p>Nesne ilk uygulama ayağa kalkarken kullanılmasa bile oluşturulur. Maliyetli bir yöntem olması yanında hız isteyen projelerde, heap space problemi olmayan projelerde tercih edilebilirsiniz.</p><p>Nesne değiştirilemeyeceği için thread safe özelliği taşımaktadır.</p><figure><img alt="Eager Singleton Initialization Sample" src="https://cdn-images-1.medium.com/max/882/1*5B8gfrx39QNoONKn6UrMLQ.png" /><figcaption>Eager Singleton Initialization — Sample</figcaption></figure><p>Sınıf ilk memory üzerine yüklenirken, sınıf içerisinde tanımlanan referans üzerinde sınıftan nesne oluşturulur ve final, static özellikleri kullanılarak direk ulaşılabilir olması ve override edilmesi engellenir. Constructor private tanımlanması ile new anahtar sözcüğü ile bu sınıftan sınıf dışından yeni nesneler oluşturulması engellenir.</p><figure><img alt="Eager Singleton Initialization Kullanımı Sample" src="https://cdn-images-1.medium.com/max/842/1*pMW-jzI69EuVIL2Ezftxzg.png" /><figcaption>Eager Singleton Initialization Kullanımı — Sample</figcaption></figure><p>Static olarak tanımlanan getInstance() metodu ile uygula başlangıç aşamasında oluşturulan nesneye erişim sağlanır, kullanılabilinir. Sample uygulama çalıştığında getInstance() ile alınan nesnelerin aynı ne olduğu, nesne düzeyinde eşitlik kontrolü sağlayan equeals() metodu ile sağlanır, “Same object. (Eager Initialization)” çıktısı console üzerinde görülecektir.</p><h3>2. Static Blok Initialization</h3><p>Eager olarak yüklenir. Nesne sınıf dışından değiştirilemeyeceği için thread safe özelliği taşımaktadır.</p><figure><img alt="Static Blok Initialization Sample" src="https://cdn-images-1.medium.com/max/727/1*YmJ-Il5P38TiLAj04I8kUA.png" /><figcaption>Static Blok Initialization — Sample</figcaption></figure><p>Final olarak tanımlanmaması, static block üzerinde uygulama sınıf bellek üzerine yüklenme aşamasında, nesnenin üretilmesi sağlandığı için kaldırılmıştır. Bu yöntemde nesne üretim aşamasında, static block içerisinde referans değerler verilebilirsiniz.</p><p>Constructur üzerinde genel olarak tüm Singleton olarak tasarımı yapılan sınıflar için kullanımı yapılan private anahtar sözcüğü ile sınıf dışında bu sınıf için nesne oluşturulması engellenmiştir.</p><figure><img alt="Static Blok Initialization Sample" src="https://cdn-images-1.medium.com/max/965/1*hNAOkA3wKntWD-B9Kf0Sdg.png" /><figcaption>Static Blok Initialization Kullanımı — Sample</figcaption></figure><p>getInstance() metodu çağrıldığında sınıfın bellek üzerine yüklenme aşamasında oluşan nesnenin dönüşü sağlandığı görülecek, console üzerinde “Same object. (Static Block Initilization)” çıktısı vermesi beklenecektir.</p><p><strong>3. Lazy Initilization</strong></p><p>Bu kulanım yönetimi özellikle uygulama içerisinde memory kısıtları bulunan ayrıca çok kullanımı olmayan sınıflar için kullanılabilinir. Özellikle uygulama ilk çalışma süresini hızlandıracaktır, fakat uygulama içinde ki performansta çok büyük etkisi olmasa bile yavaşlama olabilir, uygulamanın memory kullanımı zamanla artacaktır. Bir kez üretilen nesneler finalize olmayacağı için sürekli memory üzerinde tutulacaktır.</p><figure><img alt="Lazy Initialization — Sample" src="https://cdn-images-1.medium.com/max/583/1*XXXpZ-0SpNHKyjATvZJxBg.png" /><figcaption>Lazy Initialization — Sample</figcaption></figure><p>Lazy initialization, getInstance() metodu çağrıldığı anda, eğer bir nesne yok ise nesne üretilmesi sağlanmıştır.</p><p>Bu kullanım sırasında dikkat edilmesi gereken en önemli nokta <strong>syncronized </strong>anahtar sözcüğünü kullanımıdır. syncronized kullanımı metodun thread safe çalışmasını sağlamaktadır. Bu anahtar sözcük kullanılan metotlarda thread kontrollü şekilde çalışır, bu birazda olsa performans düşüşüne neden olabilir.</p><figure><img alt="Lazy Initialization Kullanımı — Sample" src="https://cdn-images-1.medium.com/max/823/1*61FHW3YGuZ_YnTjrbbxj5w.png" /><figcaption>Lazy Initialization Kullanımı — Sample</figcaption></figure><h3><strong>4. Lazy Initialization Optimization</strong></h3><p>Bir önceki kullanım için metot üzerinde <strong>syncronized </strong>kullanımı her metot çağrıldığında performans kaybına neden olacağını yazmıştık. Bu kullanımı kullanımı değiştirerek optimizasyon yapabiliriz.</p><figure><img alt="Lazy Initialization Optimization — Sample" src="https://cdn-images-1.medium.com/max/820/1*dt3iaj_SdiRKeTB1cAuPYQ.png" /><figcaption>Lazy Initialization Optimization — Sample</figcaption></figure><p>Kod blokunda görüldüğü gibi metot üzerinden <strong>syncronized </strong>kaldırılmıştır. Her metot çağrıldığında thread safe çalışmayacaktır, bu da performans kaybına engel olacaktır.</p><p><strong><em>volatile </em></strong><em>anahtar sözcüğü Java üzerinde tanımlanan değerlerinin memory üzerinde bir noktadan erişim sağlanacak şekilde saklanması, yazılması ve okunmasını sağlar. Bu sözcük kullanılarak </em><strong><em>double-checked-locking</em></strong><em> sağlanmış olur.</em></p><p><strong><em>volatile </em></strong><em>neden ihtiyaç duyuyoruz, neden önemli olduğu konusunda şu şekilde açıklayabiliriz. Birden fazla işlemci ile çalışan sistemlerde ki değerler, işlemcide bulunan</em><strong><em> cache memory</em></strong><em> üzerinde ayrı ayrı tutulması sağlanabilir. volatile bunu engelleyerek main memory üzerinde bir alanda olmasını garantileyerek bu cache memory yapısından kaynaklanacak olan hataları engelleyecektir.</em></p><p>Thread safe duruma gelmesi için izlenen strateji, eğer nesne üretilmedi ise sınıf üzerinde <strong>syncronized</strong> sağlanarak nesne durumu thread safe olarak kontrol edilir, üretilmesi sağlanır. Burada nesne bir kez üretildi uygulama çalışma süresince finalize olmayacağı için thread safe kontrol gerekmeyecek, performans kaybı engellenecektir.</p><figure><img alt="Lazy Initialization Optimization Kullanımı — Sample" src="https://cdn-images-1.medium.com/max/1024/1*l1Zzl-jyjiZOJgGFKCzI5g.png" /><figcaption>Lazy Initialization Optimization Kullanımı — Sample</figcaption></figure><h3><strong>5. Using By Enum</strong></h3><p>Java içerisine Java 5 ile birlikte gelen Enum sınıflar static, eager, final olarak çalışmaktadır. Enum değerlerine uygulama memory üzerine yüklenirken oluşan nesneler oluşur, singleton özelliği taşımaktadır.</p><p>Enum değerleri değiştirilemeyeceği için thread safe özelliği taşımaktadır.</p><figure><img alt="Using By Enum — Sample" src="https://cdn-images-1.medium.com/max/421/1*oSxy-4Bp4AvOLFxGQiEACQ.png" /><figcaption>Using By Enum — Sample</figcaption></figure><figure><img alt="Using By Enum Kullanımı- Sample" src="https://cdn-images-1.medium.com/max/539/1*fEKFlqkKZUkncUiBWoeskg.png" /><figcaption>Using By Enum Kullanımı — Sample</figcaption></figure><p><strong>Github Adresi :</strong> <a href="https://github.com/u-bayram/singleton-pattern">https://github.com/xenop54/singleton-pattern</a></p><p>Teşekkürler.</p><p>End Of File…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa23adacd32d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>