Java что такое factory

Java что такое factory

Я понимаю что в 1м примере с кофе нужно разделить создание экземпляров от приготовления кофе. Мне не понятно, а не проще ли просто было создать метод createCoffee в этом же классе CoffeeShop, а не городить дополнительный класс? Я не настаиваю что я прав, но хочу понять что бы разобраться. public class CoffeeShop < public Coffee createCoffee (CoffeeType type) < Coffee coffee = null; switch (type) < case AMERICANO: coffee = new Americano(); break; case ESPRESSO: coffee = new Espresso(); break; case CAPPUCCINO: coffee = new Cappuccino(); break; case CAFFE_LATTE: coffee = new CaffeLatte(); break; >return coffee; > public Coffee orderCoffee(CoffeeType type) < /*Coffee coffee = null; switch (type) < case AMERICANO: coffee = new Americano(); break; case ESPRESSO: coffee = new Espresso(); break; case CAPPUCCINO: coffee = new Cappuccino(); break; case CAFFE_LATTE: coffee = new CaffeLatte(); break; >*/ Coffee coffee = createCoffee(type); coffee.grindCoffee(); coffee.makeCoffee(); coffee.pourIntoCup(); System.out.println(«Вот ваш кофе! Спасибо, приходите еще!»); return coffee; > >

У данного примера с кофе, мы все также не решаем проблему маштабирования. Если у нас появляется новый вид кофе, то нам нужно вносить изменения в 2 класса SimpleCoffeeFactory и CoffeeType. «Если ассортимент изменится, нам не придется править код везде, где будет использоваться создание кофе. Достаточно будет изменить код только в одном месте.» — остается проблемой.

А как это дело запустить то? В мэйне мы же не можем создать экземпляр кофешоп. Статик сделать тоже не получается. Как вывести то в консоль что кофе готово?

 Хотя все могло быть еще проще, если сделать метод createCoffee статичным. Но тогда мы потеряли бы две возможности: 1. Наследоваться от SimpleCoffeeFactory и переопределять метод createCoffee . 

Почему не будет возможности наследоваться и тем более переопределять метод, если createCoffe будет с модификатором static?

Читайте также:  Display image html with link

Использовать switch тоже не совсем хорошая практика. Это претензия не к автору, почему то во всех примерах используют case. Но это как-то не красиво, да и в реальных проектах я такого не встречал

Источник

The Factory Design Pattern in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll explain the factory design pattern in Java. We describe two patterns: Factory Method and Abstract Factory. Both are creational design patterns. We’ll use an example to illustrate these patterns.

2. Factory Method Pattern

First, we need to define an example. We are working on an app for a vehicle manufacturer. Initially, we only had a client. This client built vehicles with a fuel-only engine. So, to follow the single responsibility principle (SRP) and the open-close principle (OCP), we use the factory method design pattern.

Before we jump into some code, we define a default UML diagram for this pattern:

Factory Method Pattern Default

Using the above UML diagram as a reference, we define some main concepts related to this pattern. The factory method pattern loosens the coupling code by separating our Product‘s construction code from the code that uses this Product. This design makes it easy to extract the Product construction independently from the rest of the application. Besides, it allows the introduction of new products without breaking existing code.

Let’s jump into code. First, in our example application, we define the MotorVehicle interface. This interface only has a method build(). This method is used to build a specific motor vehicle. The interface’s code snippet:

public interface MotorVehicle

The next step is to implement the concrete classes that implement the MotorVehicle interface. We create two types: Motorcycle and Car. The code for the first one is:

public class Motorcycle implements MotorVehicle < @Override public void build() < System.out.println("Build Motorcycle"); >>

In the case of the Car class, the code is:

public class Car implements MotorVehicle < @Override public void build() < System.out.println("Build Car"); >>

Then, we create the MotorVehicleFactory class. This class is responsible for creating every new vehicle instance. It’s an abstract class because it makes a specific vehicle for its particular factory. The code for this class is:

public abstract class MotorVehicleFactory < public MotorVehicle create() < MotorVehicle vehicle = createMotorVehicle(); vehicle.build(); return vehicle; >protected abstract MotorVehicle createMotorVehicle(); >

As you can notice, the method create() calls to the abstract method createMotorVehicle() to create a specific type of motor vehicle. That’s why each particular motor vehicle factory must implement its correct MotorVehicle type. Previously, we implemented two MotorVehicle types, Motorcycle and Car. Now, we extend from our base class MotorVehicleFactory to implement both.

First, the MotorcycleFactory class:

public class MotorcycleFactory extends MotorVehicleFactory < @Override protected MotorVehicle createMotorVehicle() < return new Motorcycle(); >>

Then, the CarFactory class:

public class CarFactory extends MotorVehicleFactory < @Override protected MotorVehicle createMotorVehicle() < return new Car(); >>

That’s all. Our app is designed using the factory method pattern. We can now add as many new motor vehicles as we want. Finally, we need to see how our final design looks using UML notation:

Factory Method Pattern Result

3. Abstract Factory Pattern

After our first app iteration, two new vehicle brand companies are interested in our system: NextGen and FutureVehicle. These new companies build not only fuel-only vehicles but also electric vehicles. Each company has its vehicle design.

Our current system is not ready to address these new scenarios. We must support electric vehicles and consider that each company has its design. To resolve these problems, we can use the Abstract Factory Pattern. This pattern is commonly used when we start using the Factory Method Pattern, and we need to evolve our system to a more complex system. It centralizes the product creation code in one place. The UML representation is:

Abstract Factory Pattern Default

We already have the MotorVehicle interface. Additionally, we must add an interface to represent electric vehicles. The code snippet for the new interface is:

public interface ElectricVehicle

Next, we create our abstract factory. The new class is abstract because the responsibility of object creation will be for our concrete factory. This behavior follows the OCP and SRP. Let’s jump into class definition:

public abstract class Corporation

Before we create the concrete factory for each company, we must implement some vehicles for our new companies. Let’s make some new classes for FutureVehicle company.

public class FutureVehicleMotorcycle implements MotorVehicle < @Override public void build() < System.out.println("Future Vehicle Motorcycle"); >>

Then, the electric car instance:

public class FutureVehicleElectricCar implements ElectricVehicle < @Override public void build() < System.out.println("Future Vehicle Electric Car"); >> 

We do the same for the NexGen company:

public class NextGenMotorcycle implements MotorVehicle < @Override public void build() < System.out.println("NextGen Motorcycle"); >>

Additionally, the other electric car concrete implementation:

public class NextGenElectricCar implements ElectricVehicle < @Override public void build() < System.out.println("NextGen Electric Car"); >>

Finally, we are ready to build our concrete factories. First, FutureVehicle factory:

public class FutureVehicleCorporation extends Corporation < @Override public MotorVehicle createMotorVehicle() < return new FutureVehicleMotorcycle(); >@Override public ElectricVehicle createElectricVehicle() < return new FutureVehicleElectricCar(); >>
public class NextGenCorporation extends Corporation < @Override public MotorVehicle createMotorVehicle() < return new NextGenMotorcycle(); >@Override public ElectricVehicle createElectricVehicle() < return new NextGenElectricCar(); >>

And it’s done. We complete the implementation using the Abstract Factory Pattern. Here is the UML diagram for our custom implementation:

Abstract Factory Pattern Result

4. Factory Method vs. Abstract Factory

To sum up, the Factory Method uses inheritance as a design tool. Meanwhile, Abstract Factory uses delegation. The first relies on a derived class to implement, whereas the base provides expected behavior. Additionally, it is over-method and not over a class. On the other hand, Abstract Factory is applied over a class. Both follow OCP and SRP, producing a loosely coupled code and more flexibility for future changes in our codebase. The creation code is in one place.

5. Conclusion

In conclusion, we did a walkthrough of the factory design pattern. We described the Factory Method and the Abstract Factory. We provide an example system to illustrate the use of these patterns. Additionally, we briefly compared both patterns.

As it is usual, the code snippet is over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью