Enum , Strategy pattern, Open/close principle -
Strategy design pattern -
is based upon open closed design principle, the 'O' of famous SOLID design principles. Strategy pattern allows to encapsulate possible changes in a process and encapsulate that in a Strategy class. By doing that your process (mainly a method) depends upon a strategy, higher level of abstraction than implementation. This makes your process open for extension by providing new Strategy implementation, but closed for modification, because the introduction of a new strategy doesn't require a change in a tested method. That's how it confirms open closed design principle.Strategy pattern is one of the famous pattern, which takes advantage of polymorphism, to remove switch cases and strive for open close design principle. Formally it encapsulate related algorithm, known as strategy and make them interchangeable.open/closed principle -
In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification";[1] that is, such an entity can allow its behaviour to be extended without modifying its source code.Bertrand Meyer is generally credited for having originated the term open/closed principle,[2] which appeared in his 1988 book Object Oriented Software Construction.
A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs.
A module will be said to be closed if it is available for use by other modules. This assumes that the module has been given a well-defined, stable description (the interface in the sense of information hiding).Software entities (Classes, modules, functions) should be OPEN for EXTENSION, CLOSED for MODIFICATION.
Open Closed Principle
As applications evolve, changes are required. Changes are required when a new functionality is added or an existing functionality is updated in the application. Often in both situations, you need to modify the existing code, and that carries the risk of breaking the application’s functionality. For good application design and the code writing part, you should avoid change in the existing code when requirements change. Instead, you should extend the existing functionality by adding new code to meet the new requirements. You can achieve this by following the Open Closed Principle.
The Open Closed Principle represents the “O” of the five SOLID software engineering principles to write well-designed code that are more readable, maintainable, and easier to upgrade and modify. Bertrand Meyer coined the term Open Closed Principle, which first appeared in his book Object-Oriented Software Construction, release in 1988. This was about eight years before the initial release of Java.
This principle states: “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification “. Let’s zero in on the two key phrases of the statement:
“Open for extension “: This means that the behavior of a software module, say a class can be extended to make it behave in new and different ways. It is important to note here that the term “extended ” is not limited to inheritance using the Java extend keyword. As mentioned earlier, Java did not exist at that time. What it means here is that a module should provide extension points to alter its behavior. One way is to make use of polymorphism to invoke extended behaviors of an object at run time.
“Closed for modification “: This means that the source code of such a module remains unchanged.
It might initially appear that the phrases are conflicting- How can we change the behavior of a module without making changes to it? The answer in Java is abstraction. You can create abstractions (Java interfaces and abstract classes) that are fixed and yet represent an unbounded group of possible behaviors through concrete subclasses.
An enum is a reference type (just like a class, interface and array), which holds a reference to memory in the heap. It is implicitly final, because the constants should not be changed. It can include other component of a traditional class, such as constructors, member variables and methods. (This is where Java's enum is more powerful than C/C++'s counterpart). Each enum constant can be declared with parameters to be passed to the constructor when it is created. For example,
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL = 3;
This pattern has many problems, such as:
Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.
Enums in Java
are type-safe and thus, the value of an enum variable must be one of the predefined values of the enum itself.
have their own namespace
can be used in a switch statement, in the same way as integers.
considered to be reference types, like class or Interface and thus, a programmer can define constructor, methods and variables, inside an enum.
public enum ProfileStatusEnum {
REGISTERED(1,"REGISTERED"),
CANCELLED(2,"CANCELLED"),
BANNED(3,"BANNED"),
PENALIZED(4,"PENALIZED"),
STOPPED(5,"STOPPED");
private long id;
private String name;
ProfileStatusEnum(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}
we can intilise the object by getting id from enum type.
Status status = new Status(ProfileStatusEnum.BANNED.getId());
we can use as check in code insted of constant
profileStatusID.longValue() == ProfileStatusEnum.REGISTERED.getId()
One instance of the enum class will be created to represent each item you listed, available as a static field of the class, using the name you supplied which will be the individual values. Each instance can provide an integral value, with sequential indexes starting at 0, in the order that the names were defined - there is no way to change this, but there is a route to get specific values which have a complex internal state.
Individual values from the set may be accessed as static elements of the enum class. The JVM will instantiate exactly one instance of each value from the set. Therefore, they can be used in comparisons with ==, or in switch statements (using the equals method is preferred to ==, since it will serve as a reminder that you are dealing with true objects, not integers).
Although enums may be top-level classes, they are often created as inner classes, as in the following example, where the concept of the enum is an integral part of a new BookWithEnum class. When used as an inner class, they are automatically static, so that an instance of an inner enum does not have access to instance elements of the enclosing class.
public class BookWithEnum {
private int itemCode;
private String title;
private double price;
private Category category;
public enum Category {
required,
supplemental,
optional,
unknown
};
public BookWithEnum(
int itemCode, String title,
double price, Category category) {
setItemCode(itemCode);
setTitle(title);
setPrice(price);
setCategory(category);
}
public BookWithEnum(String title) {
setItemCode(0);
setTitle(title);
setPrice(0.0);
setCategory(Category.unknown);
}
public int getItemCode() {
return itemCode;
}
public void setItemCode (int itemCode) {
if (itemCode > 0) this.itemCode = itemCode;
}
public String getTitle() {
return title;
}
public void setTitle (String title) {
this.title = title;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public void setCategory(Category category) {
this.category = category;
}
public void setCategory(String categoryName) {
this.category = Category.valueOf(categoryName);
}
public Category getCategory() {
return category;
}
public void display() {
System.out.println(itemCode + " " + title + ": " + category +
", Price: $" + price);
}
}
The Category enum is defined as an inner class to BookWithEnum. The full names of the complete set of values are: BookWithEnum.Category.required, BookWithEnum.Category.supplemental, BookWithEnum.Category.optional, and BookWithEnum.Category.unknown. From within the BookWithEnum class, they may be accessed as: Category.required, Category.supplemental, Category.optional, and Category.unknown.
Comments
Post a Comment