25 Aralık 2019 Çarşamba

Yazılım Mimarisi Microservices Architecture - Service Mesh

Giriş
Mikroservis mimarisinin 3 tane önemli unsuru var. Açıklaması şöyle
A modern cloud-native application running on Microservice Architecture relies on the following critical components:

- Containerization (through platforms like Docker) - for effective management and deployment of services by breaking them into multiple processes.
- Orchestration (through platforms like Kubernetes) - for configuration, assignment and management of available system resources to services.
- Service Mesh (through platforms like Istio) - for inter-service communication through a mesh of service- proxies to connect, manage and secure microservices.
Service Mesh Nedir?
Açıklaması şöyle.
"Service mesh" is an umbrella term for products that seek to solve the problems that microservices' architectures create. These challenges include security, network traffic control, and application telemetry.
Esas amacı servisler arası iletişim. Açıklaması şöyle
A service mesh refers to a dedicated infrastructure layer for tackling service-to-service communication. It enables reliable delivery of requests through the complex topology of services constituting a modern, cloud native application.
Yani 3 tane alanda hizmet veriyorlar. Bunlar traffic management, security, and observability.

API Gateway vs Service Mesh
Açıklaması şöyle
A service mesh’s primary purpose is to manage internal service-to-service communication, while an API Gateway is primarily meant for external client-to-service communication. 

API Gateway provides a single entry point for a client for a number of different underlying APIs (system interfaces/web services/Rest APIs, Lambdas, etc.). Performs traffic management, authorization and access control, monitoring, and API version management.

API Gateway operates at Layer 7. Just like layer 7 load balancers it knows about content. Thus induces an overhead in extra hop at API gateway.

Service Mesh (Popular example Istio) operates at layer 4. Provides inter service communication. Works like a sidecar to services. Handles service discovery, circuit breaking, timeouts, retries, encryption, tracebility, authentication and authorization among services.
İletşim (Communication)
Açıklaması şöyle
In a Service Mesh, proxies deployed alongside individual services enabling inter-service communication is widely known as the Sidecar Pattern. The sidecars (proxies) might be designed to handle any functionalities critical to inter-service communication like load balancing, circuit breaking, service discovery, etc.
Observability - Improved Transparency
Observability Nedir?
Açıklaması şöyle.
In software, observability (abbreviated as “o11y”) is the ability to ask new questions of the health of your running services without deploying new instrumentation. The term comes from control theory, which defines observability as the ability to understand the internal state of a system from its external outputs (source).

Telemetry consists of those “outputs”—it’s the data generated by your system that documents its state.
Şekilde Linkerd service mesh dashboard'unda service çağrıları görülebilir


Telemetry Ne Anlama Gelir?
Açıklaması şöyle. 
The term comes from the Greek tele-, meaning “remote”, and -metry, meaning “measure.” You probably already generate telemetry from your programs, even if you’re not paying for monitoring or logging services. In fact, even the output from a print or console.log() statement is a form of telemetry!
Telemetry olarak
- Metrics
- Application Performance Monitoring (APM)
- Loglar
- Traces
- Structured Events
kullanılabilir
Telemetry Olarak Metrics Nedir?
Açıklaması şöyle. 
One commonly used form of telemetry data in software is metrics. A metric consists of a single numeric value tracked over time. Traditional monitoring uses system-level metrics to track things like CPU, memory, and disk performance. This data is important for choosing among virtual machine instance types, with options for processor speed, RAM, and hard disk storage. 
Telemetry Olarak Application Performance Monitoring (APM) Nedir?
Açıklaması şöyle.  Metrics'in yetersiz kaldığı durumda, uygulamanın kendisi hakkında bilgi verir.
But it doesn’t tell you about user experience, or how to improve the performance of your code.

Modern monitoring services also provide application performance monitoring (APM) features, which track application-level metrics like average page load times, requests per second, and error rates. Each metric only tracks one variable, which makes it cheap to send and store. Values are pre-aggregated at write-time, however, so you need to deploy a code change if you want to track metrics for a new intersection of data, e.g. error rates for a specific user.
APM verisi genellikle "time-series" veritabanı üzerinde saklanır.

Telemetry Olarak Log
Açıklaması şöyle. 
Logs are text strings written to the terminal or to a file (often referred to as a “flat” log file). Logs can be any arbitrary string, but programming languages and frameworks have libraries to generate logs from your running code with relevant data at different levels of specificity (e.g. INFO vs. DEBUG mode). There’s no standardization among programming communities about what should get included at each log level.

Log aggregation services allow you to send the content of your logs and store them for later retrieval. Querying flat logs (as opposed to structured logs) is slow because of the computational complexity of indexing and parsing strings, which makes these tools impractical for debugging and investigating your production code in near-realtime.
Telemetry Olarak Traces
Açıklaması şöyle. 
A trace is a visualization of the events in your system showing the calling relationship between parent and child events as well as timing data for each event. The individual events that form a trace are called spans. Each span stores the start time, duration, and parent_id. Spans without a parent_id are rendered as root spans.

A distributed trace connects calling relationships among events in distributed services. For example, Service A calls Service B, which makes a database query and then hits a third-party API.
Telemetry Olarak Structured Events Nedir?
Açıklaması şöyle. 
A structured event is a data format that allows you to store key-value pairs for an arbitrary number of fields or dimensions, often in JSON format. At a minimum, structured events usually have a timestamp and a name field. Instrumentation libraries can automatically add other relevant data like the request endpoint, the user-agent, or the database query.

When we talk about wide events, we mean structured events with lots of fields. You can add whatever fields you want, and because they’re key-value pairs, it’s easy to query for them later on.

Events can be built into traces by pointing each event to its parent event with the parent_id field.
Telemetry Verisinin Özellikleri
Telemetry verisinin
- Context 
- Dimensionality 
- Cardinality 
gibi özellikleri de önemli
Telemetry Context Nedir?
Açıklaması şöyle. 
Context refers to the collection of additional dimensions, fields, or tags on a piece of data that tells you more about the internal state of your system. Context can include metadata, system-level metrics, and domain-specific information about the running program.
Telemetry Dimensionality Nedir? - Verinin Kaç Farklı Sütunu Var Gibi Düşünülebilir
Açıklaması şöyle. 
The dimensionality of data refers to how many fields or attributes a piece of data has attached to it. Examples of low-dimensionality data include metrics and flat logs. High-dimensionality data includes anything that can support many fields or attributes, including JSON blobs, structs, and objects.
Telemetry Cardinality  Nedir? - Her Sütun Kaç Farklı Değer Alabilir Gibi Düşünülebilir
Açıklaması şöyle. 
The term cardinality refers to how many possible values a dimension can have. Some examples of low-cardinality data include booleans (true/false) and days of the week. High-cardinality examples are first name, social security number, UUID, or build ID.

Cardinality becomes especially relevant when you start considering multiple dimensions at the same time. For a REST API, for example, endpoints can number from dozens or hundreds (not including unique IDs). If you want to look at the behavior of each endpoint across the over 43 million user agents in the world, you get what’s called a cardinality explosion. Imagine trying to track the intersection of endpoint × user agent with application-level metrics—that’s billions of lines of code. Thus when you have questions that require high-cardinality data to answer, you need telemetry and tools that support it.
 Sadece Telemetry Yeterli mi?
Açıklaması şöyle. Cevap hayır. Yardımcı araçlar da gerekir.
In order to have good observability into your software services, you need both good instrumentation generating high-context telemetry data, and you need sophisticated ways of interacting with that data that enable asking novel questions—questions you couldn’t have thought of when you wrote the code. Put more simply, software observability requires good data and good tooling.
Service mesh Observability yeteneğine yardımcı olur. Açıklaması şöyle
It isn’t easy to follow the complex flow of traffic behavior within an unclear and dense cloud-native environment. Messages take a winding path through the topology, moving between the infrastructure layers and transitioning from pod to pod on a unique track. This is where service mesh brings transparency to the way application modernization services are delivered. You can thus track their behavior effectively.
Bazı Service Mesh Ürünleri
Bazı çözümler şöyle
The leading solutions today are:

- Istio: A full open-source solution founded by IBM, Google and Lyft.
- App Mesh: Exclusive to AWS.
- Linkerd: Initially developed by Twitter for internal use, in 2017 it was made open-source and donated to the CNCF.
- Consul Connect: Open-source with a premium paid service.
- SMI (Microsoft Service Mesh Interface): Announced at KubeCon in 2019, it is backed by heavy players such as Linkerd, HashiCorp, Colo.io, and VMWare.
Nasıl Çalışır
Açıklaması şöyle
Service Mesh katmanını sağlamanın 3 farklı yolu mevcut.
- Mikroservis uygulamasına non functional kod yazarak veya dependency olarak kütüphaneler ekleyerek (Hystrix, Ribbon, Feign client gibi)
- Node agentlar aracılığıyla nodelar üzerinde denetimler sağlayarak
- Ya da Sidecar Proxy’ler aracılığı ile.
Sidecar Proxy Nedir?
Açıklaması şöyle. Yani pod üzerinde iki tane container oluyor. İkinci contaier sidecar proxy container
What is a sidecar pattern?
The sidecar pattern is a single-node(pod) pattern that has two containers. The first is the application container. It contains the core business logic for the application. In addition to the application container, there is a sidecar container. The role of the sidecar is to augment the application container.
Açıklaması şöyle
Sidecar Proxy’ler adından da anlaşılacağı üzere aslında birer proxy. Servislerin yanına konumlanırlar. Servisler hedef servislere erişimlerini o servise ait sidecar proxy üzerinden sağlarlar. Sidecar’ları sadece servis intercommunication’ı değil; load balancing, service discovery, authorization, authentication gibi konuları da çözen bir kutu olarak düşünebiliriz. Örneğin balancing üzerinden konuşursak, 3er instance çalışan listeleme ve stok servislerinden 2 stok servisi bottleneck içerisinde ise sidecarlar gelen istekleri daha stabil olan 3. containera yönlendirme aksiyonunu gerçekleştirebilirler. Sidecarlarınız Kubernates gibi bir orchestration frameworkünde yönetiliyorsa OSI 4. katmanda load balancing işlemleri gerçekleştirilir. Bu da bir yazılımcının bunu kodlamasından daha hızlı sonuçlar ortaya çıkaracaktır. Ayrıca servis sayısının artması durumunda servisler arası iletişimin daha güvenilir olmasını sağlayacaktır.
Yani sidecar proxy
- service intercommunication : Hiç bir servis birbirini direkt çağırmaz.
- load balancing
- service discovery
- authorization
- authentication
gibi işlevleri yerine getirir
Şeklen şöyle


Sidecar Proxy Çeşitli Dillerde Olabilir
Açıklaması şöyle
... for example envoy proxy is used in AWS App mesh and Istio is implemented in C++ & Linkerd’s micro proxy is implemented in Rust
Şekle şöyle. Burada sidecar proxy'lerin farklı teknolojilerle geçekleştirildiği görülebilir.



Sidecar Proxy Servisleri
Şeklen şöyle. Burada sidecar proxy tarafından sağlanan log, discovery gibi hizmetler görülebilir.

Sidecar Proxy yine Service Mesh tarafından sağlanan Control Plane ile haberleşir. Şeklen şöyle







23 Aralık 2019 Pazartesi

Redis - Redisson

Giriş
Açıklaması şöyle
Redisson is a very handy library that provides distributed Java objects and services on top of Redis.

It supports cluster, AWS Elasticache, Sentinel, master/slave and single connection modes. The Redisson project was created and is being maintained by Nikita Koksharov.
Sanırım Redis'in cluster olarak kullanımını kolaylaştırıyor.

Maven
Şu satırı dahil ederiz
<dependency>
   <groupId>org.redisson</groupId>
   <artifactId>redisson</artifactId>
   <version>3.17.6</version>
</dependency>
delayqueue Arayüzü
Açıklaması şöyle
redisson delayqueue is a delay queue implementation based on the redis zset structure. delayqueue has an ordered collection called timeoutSetName where the score of the elements is the delivery timestamp. delayqueue regularly scans for messages that have reached delivery time using zrangebyscore and then moves them to the list of ready messages.

The delayqueue guarantees that redis will not lose messages without crashing, and may be worth a try in the absence of a better solution.

With a well-designed database index, the overhead incurred by regularly scanning the database for unfinished orders is not as large as one might think. Timed task middleware such as redisson delayqueue can be used along with scanning the database as a compensation mechanism to avoid task loss due to middleware failures.
Distributed Lock
Açıklaması şöyle. Distributed Lock için bir thread çalıştırır ve bu thread TTL değerini hep ileri atar. Böylecek lock bayatlamaz. 
A more generalized solution is that once a client holds the lock, it starts a daemon thread to periodically check if the lock exists. If so, the daemon thread will reset the TTL to prevent lock auto-release. This strategy is sometimes referred to as the lease strategy, meaning that a lock is only leased to a client with a fixed lease length, and before lease expiration, client should renew the lease if the lock is still needed. For example, open source solution Redisson uses this strategy. 
...
A WatchDog daemon thread is started once a lock is acquired. This background thread periodically checks if client still holds the lock and resets the TTL accordingly. This strategy helps to prevent pre-mature lock release.
RBlockingQueue Arayüzü
ExecutorService ile birlikte kullanılabilir.

RBloomFilter Arayüzü
Bu sınıfın kardeşi RClusteredBloomFilter arayüzü. Sadece clustered ortamda kullanılabilir. Açıklaması şöyle.
Redisson also supports distributed Bloom filters in Redis via the RClusteredBloomFilter interface. The RClusteredBloomFilter is more memory-efficient, shrinking the memory used across all Redis nodes. An RClusteredBloomFilter object may contain up to 2^64 bits. Note that the  RClusteredBloomFilter is only available in Redisson's cluster mode.
contains metodu
Örnek
Şöyle yaparız.
RBloomFilter<SomeObject> bloomFilter = redisson.getBloomFilter("sample");
// initialize Bloom filter with  expectedInsertions = 55000000  falseProbability = 0.03
bloomFilter.tryInit(55000000L, 0.03);


bloomFilter.add(new SomeObject("field1Value", "field2Value"));
bloomFilter.add(new SomeObject("field5Value", "field8Value"));
bloomFilter.contains(new SomeObject("field1Value", "field8Value"));
bloomFilter.count();

RedissonSessionManager Sınıfı
org.redisson.tomcat.RedissonSessionManager sınıfı Tomcat session bilgisini Redis cluster'ında saklayabilir.

RedissonClient  Sınıfı
Örnek
Şöyle yaparız
@RequiredArgsConstructor
@Configuration
public class RedissonConfig {

  @Bean
  public RedissonClient redissionClient() {
    Config config = new Config();
    config.useSingleServer().setAddress("redis://127.0.0.1:6379");
    return Redisson.create(config);
  }
}

private final RedissonClient redisson;
RLock lock = redisson.getLock("update-stock-lock");
lock.lock(4, TimeUnit.SECONDS);
  ...
lock.unlock();

1. Asenkron Kodlama
RFuture Sınıfı
Açıklaması şöyle.
In Redisson, each asynchronous method returns an RFuture object, which represents the result of an asynchronous computation. RFuture implements the java.util.concurrent.Future and java.util.concurrent.CompletionStage interfaces in Java.

2. Reactive Kodlama
Mono Sınıfı
Açıklaması şöyle.
In Redisson, each reactive method returns a reactor.core.publisher.Mono object, which signals that it has successfully completed the computation by emitting an element.



19 Aralık 2019 Perşembe

X509 Dijital Sertifika

Giriş
X509 en yaygın dijital sertifika standardı. Açıklaması şöyle.
There are many certificate formats that could be used by a key management system; one of the most common is the X509 format. X509 has gone through a few revisions; the version supported by the Java API is version 3. This format is an ANSI standard for certificates, and while there are PGP and other certificate formats in the word, the X509 format is dominant. This is the only format of certificate for which Java provides a standard API; if you want to support another certificate format, you must implement your own subclass of Certificate.
Açıklaması şöyle.
An X.509 certificate binds a name to a public key value. The role of the certificate is to associate a public key with the identity contained in the X.509 certificate.
Sürümleri
İlk X.509 standardı 1988 yılında yayınlandı ve bir çok RFC dokümanına yayılmış vaziyette. X.509 için 3 sürüm var. v1, v2 ve v3.

v1
İlk sürüm X.500'den ilham alıyor. Açıklaması şöyle
The reason certificates have the metadata they do is historical. Certificates are defined in the X.509 standard from the ITU-T. It is part of implementation of the X.500 standard, the Directory services. It’s also related to another standard called LDAP

These technologies were designed at the beginning of the internet (1988) and have a strong backing in the telephone networks.

The X.500 family of standards were created to facilitate directory services (think phone books). For these it makes sense to record where someone is located in order to tie some arbitrary data (like a phone number) to a physical location or name (like address and name of user).
Directory Services için düşünülen ancak hayata geçmeyen yöntem şöyle
AFAIK the original idea was that there would be one Global X.500 Directory, branching out almost exactly like how DNS works nowadays – e.g. France would be delegated the C=FR subtree; Microsoft would manage the O=Microsoft,C=US subtree; and so on. 

Correct. That was the original, never fully implemented plan for DAP. It’s why we got LDAP. It would not be directly linked to just the C & O records but also by the issuer records.
v3
Açıklaması şöyle. Sertifika ASN.1 formatındadır.
x509 v3 certificates have extensions which are an ASN.1 sequence containing an OID, a critical flag, and an octetString called extnValue.
Sertifika tabiki ASN.1 formatında gönderilemez. Bunun için DER encoding kullanılır.

Sertifika Çeşitleri
Sertifika alırken şu çeşitler olabilir.
Domain Validated (DV)
Organization Validated (OV)
Extended Validation (EV)
Sertifika Zinciri
Şöyledir.
GeoTrust Global CA
   Google Internet Authority G2
      *.google.com
Common Name - Artık Deprecated Sayılabilir
Açıklaması şöyle. Sunucu ismi veya kullanıcı ismi gibi düşünülebilir. Bu alan yerine artık subjectAltName kullanılıyor. Çünkü bir çok sunucu artık tek bir alan ismi yerine birden fazla alan ismini sunuyor. 
The Common Name (AKA CN) represents the server name protected by the SSL certificate. The certificate is valid only if the request hostname matches the certificate common name. Most web browsers display a warning message when connecting to an address that does not match the common name in the certificate.

In the case of a single-name certificate, the common name consists of a single host name (e.g. example.com, www.example.com), or a wildcard name in case of a wildcard certificate (e.g. *.example.com).

The common name is technically represented by the commonName field in the X.509 certificate specification.
Bir başka açıklama şöyle
Originally certificates were only valid for a single name. But with the growth of the web, it was very common that the same server would be accessible under multiple names. So certificates were extended to permit multiple names. The use of the Common Name (CN) field has been deprecated since 2000 in favor of the subjectAltName field (Subject Alternative Name, often abbreviated SAN). The subjectAltName field can contain a list of names (or name patterns starting with a wildcard), not just a single name.

The subjectAltName field for the certificate offered by https://stackoverflow.com/ includes stackoverflow.com as well as *.stackexchange.com, *.stackoverflow.com, *.meta.stackexchange.com, etc. Chrome recognizes stackoverflow.com in the subjectAltName field. It's a bit weird that it only shows the CN value in the overview, but you can view the certificate details and see the SAN entries under “*.stackexchange.com” → “Certificate” → “Extensions” → “Certificate Subject Alternative Name”.

Issuer Name
Certificate Authority (CA) adı. "Issued By" olarak bilinir. "Common Name", "Organization" olarak gösterilir.

Örnek
Şöyle görürüz.
Issuer: CN=ABC XYZ, O=ABC, C=IN

Private Key
Sertifikayı kullanan kişinin anahtarı. Bu nesnede Modulus+Public Exponent+Private Exponent bilgileri vardır.

Public Key
Sertifikayı kullanan kişinin anahtarı. Bu nesnede Modulus+Public Exponent vardır.

Serial Number
Certificate Authority (CA) tarafından atanan seri numara.

Subject Name
Sertifikayı kullanan kişinin adı

Subject Alternative Name (subjectAltName) - Etkin Kullanılan Alan Bu
Sunucu ismi veya kullanıcı ismi gibi düşünülebilir. Aynı sertifikanın bir çok farklı alan ismi ile kullanılabilmesini sağlar. Açıklaması şöyle
The common name can only contain up to one entry: either a wildcard or non-wildcard name. It’s not possible to specify a list of names covered by an SSL certificate in the common name field.

The Subject Alternative Name extension (also called Subject Alternate Name or SAN) was introduced to solve this limitation. The SAN allows issuance of multi-name SSL certificates.

The ability to directly specify the content of a certificate SAN depends on the Certificate Authority and the specific product. Most certificate authorities have historically marketed multi-domain SSL certificates as a separate product. They’re generally charged at a higher rate than a standard single-name certificate.

On the technical side, the SAN extension was introduced to integrate the common name. Since HTTPS was first introduced in 2000 (and defined by the RFC 2818), the use of the commonName field has been considered deprecated, because it’s ambiguous and untyped.

The CA/Browser Forum has since mandated that the SAN would also include any value present in the common name, effectively making the SAN the only required reference for a certificate match with the server name. The notion of the common name survives mostly as a legacy of the past. There are active discussions to remove its use from most browsers and interfaces.
Aslında Client ve Server sertifikaları arasındaki en önemli fark ta bu alan. Açıklaması şöyle
Structurally, client and server certs are the same. Both will need keyUsage: digitalSignature and will contain the same type of RSA or ECDSA key. They chain to an intermediate and root CA via Issuer and AIA fields in exactly the same way as server certs. They handle revocation via CRL or OCSP in exactly the same way as server certs.

However, depending on the enforcement / authorization rules in your server, you may need to put different metadata in the client certs. For example:

- Server certs almost always have a SubjectAltName of type dNSName matching the public domain name at which the server can be reached. This makes absolutely no sense for a client. Often instead you see a serialNumber DN component, or one of the less common SAN types.
- Your server may be configured to require client certs to have the extendedKeyUsage: id-kp-clientAuth.
- Your server may enforce groups, privileges or access controls based on policy OIDs or other custom v3 extensions.
Örnek
Bir örnek şöyle
The StackOverflow certificate has got a subjectAltName field with the following dNSNames in it, which allow the certificate to validate for StackOverflow.

*.askubuntu.com
*.blogoverflow.com
*.mathoverflow.net
*.meta.stackexchange.com
*.meta.stackoverflow.com
*.serverfault.com
*.sstatic.net
*.stackexchange.com
*.stackoverflow.com
*.stackoverflow.email
*.stackoverflowteams.com
*.superuser.com
askubuntu.com
blogoverflow.com
mathoverflow.net
openid.stackauth.com
serverfault.com
sstatic.net
stackapps.com
stackauth.com
stackexchange.com
stackoverflow.blog
stackoverflow.com
stackoverflow.email
stackoverflowteams.com
stacksnippets.net
superuser.com

Security
Şu seviyeler olabilir.
DV = only domain name control is verified.
OV = owner entity (organization) information is verified in addition.
EV = more thorough version of OV, which has traditionally been awarded with the "green bar" (but the "green bar" appears to be going away soon).
Eğer EV yoksa şuna benzer bir çıktı alırız.
X509v3 Extended Key Usage:
TLS Web Server Authentication, TLS Web Client Authentication
ThumbPrint
Sertifikanın bir parçası değildir. tbsSertificate + signatureAlgorithm (CA tarafından imzalamak için kullanılan algoritma) + signatureValue değerlerinin tek yönlü bir hash'ten geçirilerek elde edilen değerdir. ThumbPrint sertifkaları kolayca aramak için kullanılır.


GoF - Strategy Örüntüsü

Strategy Ne Değildir
Strategy ana algoritmayı gerçekleştiren sınıftan kalıtım değildir! Bu anlayış tamamen yanlış.

Kalıtım varsa bunun ismi Template Method Örüntüsüdür. Strategy ana algoritmayı gerçekleştiren sınıfa takılan davranıştır. Açıklaması şöyle.
Imagine you design a Cache. The cache can have options regarding

- eviction policy (LIFO, FIFO, LRU)
- expiration policy (after read, after write)
- maximum size (number of elements, memory usage)

Now imagine you want to let the user of your cache choose any of these options, and you use inheritance. You'll need 3 * 2 * 2 = 12 different classes:

- LifoAfterReadNumberOfElementsBasedCache,
- LifoAfterReadMemoryBasedCache,
-  etc.

Each of the 4 LifoXxx classes will have to implement the same algorithm to implement the LIFO strategy. Same for the other ones.

Implement it with the strategy pattern instead of inheritance, and you'll have a single Cache class, and 7 strategy classes (one for each strategy), that you can combine however you want, and without code duplication.
Strategy Nedir
Strategy ile tanımlanan arayüze uygun, farklı davranışlar gerçekleştiren sınıflar yazılır. Ve bu sınıflar ana algoritmayı çağıran sınıfa takılırlar. Strategy sınıfları genellikle bir Factory aracılığıyla yaratılır.

Stategy'lerin Parameterik Olması
Örnek
Elimizde şöyle bir kod olsun
public abstract class Temperature {
  public abstract double convert(Temperature to) throws AbsoluteZeroException;
}
Bu sınıftan kalıtan şöyle alt sınıflar olsun
public class Celsius extends Temperature {
  @Override
  public double convert(Temperature to) {
    ...
  }
}
ve
public class Fahrenheit extends Temperature {
 
  @Override
  public double convert(Temperature to) throws AbsoluteZeroException {
    ...
  }
}
Her strategy bir Temperature nesnesi alıyor ancak birimi belli değil.

Çözüm 1
Şöyle yaparız. Her strategy kendi değerini kelvin'e veya başka ortak bir değere çevirir. Ana sınıf bu değerden okur.
public static Temperature convert(Temperature from, TemperatureScale to) {
  double kelvin = from.toKelvin();
  return to.fromKelvin(kelvin);
}
Çözüm 2
Şöyle yaparız. Belki de strategy kullanmaya gerek bile yoktur. Her sınıf kullandığı birimi bilir. Geri kalan her şey parametriktir :)
Tempature celcius = new Tempature(98.6, TempatureType.CELSIUS);
Tempature fahrenheit = Tempature.convert(tempatureCels, TempatureType.FAHRENHEIT);
Enumeration ile Strategy Üretmek
Örnek - Sadece Enum Kullanmak
Şöyle yaparız
public enum FileType {
  EXCEL(".xlsx") {
    @Override
    public void download() {
    }
  },
  CSV(".csv") {
    @Override
    public void download() {
    }
  },
  private String suffix;

  FileType(String suffix) {
    this.suffix = suffix;
  }

  public String getSuffix() {
    return suffix;
  }

  public abstract void download();
}

@GetMapping("/exportOrderRecords")
public void downloadFile(User user, HttpServletResponse response) {
  ...
  String fileType = user.getFileType();
  FileType type = FileType.valueOf(fileType);
  if (type!=null) {
    type.download();
  } else {
    FileType.CSV.download();
  }
}
Örnek - EnumMap
Burada yine bir Strategy arayüzü var ve her strategy kalıtımı için de bir Enum var. Aşağıdaki gibi Strategy sınıfları olsun
public interface class IStrategy {
}
public class DistanceStrategy implements IStrategy {
}
public class PowerStrategy implements IStrategy {
}
Bu sınıflar stateless ise Java'da EnumMap başka dillerde ise herhangi bir Map veri yapısına önceden doldurulurlar ve istenilince döndürülürler
enum DataPresenterStrategyType { DISTANCE, POWER }

static EnumMap<DataPresenterStrategyType, IStrategy> lookupStrategy = new EnumMap();
{
  lookupStrategy.put(DISTANCE, new DistanceStrategy());
  lookupStrategy.put(POWER, new PowerStrategy());
}

DataPresenterStrategy toStrategy(StrategyType type) {
  return lookupStrategy.get(type);
}
Eğer sınıflar statefull ise her seferinde yeni bir nesne yaratmak gerekir. Bu durumda Java 8 ile gelen Supplier arayüzü kullanılabilir. Örnekte Supplier ile Method Expression kullanılıyor.
enum DataPresenterStrategyType { 
  DISTANCE(DistanceStrategy::new), POWER(PowerStrategy::new);
  private final Supplier<DataPresenterStrategy> constructor;

  DataPresenterStrategyType(Supplier<DataPresenterStrategy> constructor){
    this.constructor = constructor;
  }

  DataPresenterStrategy newStrategy() {
    return constructor.get();
  }
}
Strategy ve Functional Programming
GoF - Strategy Örüntüsü - Functional Java yazısına taşıdım

Strategy ve Dependency Injection
Dependency Injection altyapılarında strategy nesneleri bean ise bir kere yaratılır. Bun nesneleri kullanan bir başka bean'e inject etmek bile problem olabilir.

Aynı anda Etkin Birden Fazla Strategy'e Sahip Olmak
Normalde strategylerden sadece bir tanesi etkindir. Her strategy birbiriyle yer değiştirebilen nesne anlamına gelir. Bir nesneye farklı roller eklenebiliyorsa her role strategy demek yanlıştır. Nesneye bir çok rol çalışma zamanında eklenip çıkarılabilir. Bu durumda Decorator Örüntüsüne başvurmak gerekir.