Factory Design Pattern Nedir

0 views
Skip to first unread message

Yazmín Bohon

unread,
Aug 4, 2024, 2:31:49 PM8/4/24
to bilbtingdowsnull
Inobject oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact class. Rather than by calling a constructor, this is done by calling a factory method to create an object. Factory methods can either be specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes. It is one of the 23 classic design patterns described in the book Design Patterns (often referred to as the "Gang of Four" or simply "GoF") and is sub-categorized as a creational pattern.[1]

Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.


The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.[2]As shown in the C# example below, the factory method pattern can also rely on an Interface - in this case IPerson - to be implemented.


In the above UML class diagram, the Creator class that requires a Product object does not instantiate the Product1 class directly.Instead, the Creator refers to a separate factoryMethod() to create a product object,which makes the Creator independent of which concrete class is instantiated.Subclasses of Creator can redefine which class to instantiate. In this example, the Creator1 subclass implements the abstract factoryMethod() by instantiating the Product1 class.


Room is the base class for a final product (MagicRoom or OrdinaryRoom). MazeGame declares the abstract factory method to produce such a base product. MagicRoom and OrdinaryRoom are subclasses of the base product implementing the final product. MagicMazeGame and OrdinaryMazeGame are subclasses of MazeGame implementing the factory method producing the final products. Thus factory methods decouple callers (MazeGame) from the implementation of the concrete classes. This makes the "new" Operator redundant, allows adherence to the Open/closed principle and makes the final product more flexible in the event of change.


In the above code you can see the creation of one interface called IPerson and two implementations called Villager and CityPerson. Based on the type passed into the PersonFactory object, we are returning the original concrete object as the interface IPerson.


You can see we have used MakeProduct in concreteFactory. As a result, you can easily call MakeProduct() from it to get the IProduct. You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.


In the above snippet, the MazeGame constructor is a template method that makes some common logic. It refers to the makeRoom factory method that encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, it suffices to override the makeRoom method:


Another example in PHP follows, this time using interface implementations as opposed to subclassing (however, the same can be achieved through subclassing). It is important to note that the factory method can also be defined as public and called directly by the client code (in contrast with the Java example above).


Design pattern'lar geliştirme yaparken tekrar eden problemlere denenip onaylanıp zm olarak sunulan kalıplardır. İyi bir tasarım deseni; yazmış olduğumuz kodları temiz, okunabilir kılıp sizden sonra gelecek olan kişilere daha kolay adapte olmayı sağlamalıdır.


Bu yazıda object oriented programming'in en ok tercih edilen design pattern'lerin den biri olan Creational pattern'ler grubundan Factory Pattern'i nedir ne değildir nasıl implemente edilir rnek proje ile inceleyeceğiz.


Gang of Four patternleri gnmz dnyasında en sıkı şekilde takip edilip en ok kullanılan nl tasarım desenleridir. Factory pattern'de bu 4 l den biridir. Kısaca tanımı ; aynı abstract sınıf veya interface'den treyen nesnelerin retiminden sorumlu yapıdır. Bu pattern ile nesne yaratılma işini inheritance yoluyla client-side'dan ayırıp sub-classes'lara vermek amalanır.


Geliştirmekte olduğunuz uygulamaya yeni bir feature eklerken en az dokunuş ile client'ı bu duruma hi sokmadan yapabilmek amalanır ve factory pattern de bu amaca ynelik olarak nerilen en nemli pattern'lerden birisidir.


rnek bir case zerinden ilerleyelim. Ara retimi yapan bir fabrikamız olsun. Bu fabrika car, truck ve motorcycle retebiliyor olsun. İlk olarak factory nesnelerimizin kullanacağı IVehicleFactory interface'ini ve car, truck, motorcycle nesnelerini oluşturalım.


Yukarıdaki gibi nesneleri ve arayzleri oluşturduktan sonra ismi VehicleFactory olan ve ierisinde geriye IVehicle dndren ProduceVehicle adında bir sınıf tanımlayacağız. ProduceVehicle metodu VehicleType adında bir bir enum parametre olarak alacak. Bu enum'ı kullanarak factory metoduna retmesini istediğimiz tip bilgisini geeceğiz.




Factory metotlarımız da hazır artık retime başlayabiliriz. Client dediğimiz kısım aslında tam da aşağıdaki kod paraları oluyor Program.cs ierisinde aşağıdaki gibi retmek istediğimiz trdeki aracı factory'e syleyip retebiliriz.


Yazımızın başında da bahsettiğimiz gibi yapılabilecek değişikliklerden client'ı etkilemeden yapabilmek birinci nceliğimizdir. Bu rneğimizde araba retimi yapmak iin IVehicle interface'ini implement eden Car nesnesini kullandık ancak ilerde bir gn yine IVehicle interface'ini implement eden XCar adında bir nesne oluşturup retim yaparken bu nesnyi kullanabiliriz ve bu durum client aısından hi bir değişikliğe gidilmeden yapılabilmektedir.


The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all variants of products follow those interfaces. For example, all chair variants can implement the Chair interface; all coffee table variants can implement the CoffeeTable interface, and so on.


Now, how about the product variants? For each variant of a product family, we create a separate factory class based on the AbstractFactory interface. A factory is a class that returns products of a particular kind. For example, the ModernFurnitureFactory can only create ModernChair, ModernSofa and ModernCoffeeTable objects.


The client code has to work with both factories and products via their respective abstract interfaces. This lets you change the type of a factory that you pass to the client code, as well as the product variant that the client code receives, without breaking the actual client code.


Concrete Products are various implementations of abstract products, grouped by variants. Each abstract product (chair/sofa) must be implemented in all given variants (Victorian/Modern).


This example illustrates how the Abstract Factory pattern can be used for creating cross-platform UI elements without coupling the client code to concrete UI classes, while keeping all created elements consistent with a selected operating system.


The Abstract Factory interface declares a set of creation methods that the client code can use to produce different types of UI elements. Concrete factories correspond to specific operating systems and create the UI elements that match that particular OS.


It works like this: when an application launches, it checks the type of the current operating system. The app uses this information to create a factory object from a class that matches the operating system. The rest of the code uses this factory to create UI elements. This prevents the wrong elements from being created.


In a well-designed program each class is responsible only for one thing. When a class deals with multiple product types, it may be worth extracting its factory methods into a stand-alone factory class or a full-blown Abstract Factory implementation.


Create factory initialization code somewhere in the app. It should instantiate one of the concrete factory classes, depending on the application configuration or the current environment. Pass this factory object to all classes that construct products.


Builder focuses on constructing complex objects step by step. Abstract Factory specializes in creating families of related objects. Abstract Factory returns the product immediately, whereas Builder lets you run some additional construction steps before fetching the product.


You can use Abstract Factory along with Bridge. This pairing is useful when some abstractions defined by Bridge can only work with specific implementations. In this case, Abstract Factory can encapsulate these relations and hide the complexity from the client code.


A factory is simply a wrapper function around a constructor (possibly one in a different class). The key difference is that a factory method pattern requires the entire object to be built in a single method call, with all the parameters passed in on a single line. The final object will be returned.


A builder pattern, on the other hand, is in essence a wrapper object around all the possible parameters you might want to pass into a constructor invocation. This allows you to use setter methods to slowly build up your parameter list. One additional method on a builder class is a build() method, which simply passes the builder object into the desired constructor, and returns the result.

3a8082e126
Reply all
Reply to author
Forward
0 new messages