26 Commits

Author SHA1 Message Date
javadevjournal
f7bb0112ad Merge pull request #68 from mayank4all/master
march articles code review
2023-04-27 07:49:00 -07:00
javadevjournal
b8011dbbf5 Merge pull request #67 from KunwarVikas/stackandqueue
Behavioral Design Pattern - Observer Pattern
2023-04-27 07:48:34 -07:00
Mayank Agarwal
8a571e9a39 Added examples for java basics module 2023-04-01 17:42:50 +05:30
Mayank Agarwal
5f09e78f92 march articles code review 2023-03-18 09:37:04 +05:30
KunwarVikas
d3705724fa Behavioral Design Pattern - Observer Pattern 2023-03-12 19:14:45 +05:30
javadevjournal
44bb31c1d6 Merge pull request #66 from mayank4all/java_articles
Adding java string basic methods
2023-03-04 10:30:07 +05:30
Mayank Agarwal
b59fdf2e29 Adding java string basic methods 2023-03-04 00:15:35 +05:30
javadevjournal
db023b8db8 Merge pull request #64 from KunwarVikas/stackandqueue
Composite Design Patterns
2023-02-26 13:36:18 +05:30
javadevjournal
d2c169925f Merge pull request #65 from mayank4all/java-basics
Added program for Java Basics
2023-02-04 16:56:52 +05:30
Mayank Agarwal
d09fb927ea Added code for java basics 2023-02-03 00:57:35 +05:30
Mayank Agarwal
c518f76628 Added switch and ternary operators in java 2023-01-30 00:15:04 +05:30
Mayank Agarwal
f040615faf Added progra for Java If else 2023-01-29 12:42:11 +05:30
javadevjournal
202bce2d2b Update README.md 2023-01-22 03:23:24 -08:00
KunwarVikas
a7ae8d782b Behavioral Design Pattern - Chain of Responsibility Pattern 2023-01-01 14:49:16 +05:30
KunwarVikas
d281e8c609 Behavioral Design Pattern - Template Method Pattern 2022-11-27 18:15:31 +05:30
Kunwar
cbf785c3a3 Bridge Design Patterns 2022-10-26 20:49:43 +05:30
Kunwar
212d8b1aea Composite Design Patterns 2022-10-25 14:16:49 +05:30
javadevjournal
a584c7bee6 Merge pull request #63 from honeykakkar/patch-1
Update lambda expression used for comparator
2022-10-09 12:17:51 -07:00
Honey Kakkar
74f92e758d Update lambda expression used for comparator
Updating lambda expression in order to obtain natural ordering of customers based on their age
2022-09-21 13:39:01 +00:00
javadevjournal
ddebe806c4 Merge pull request #62 from KunwarVikas/stackandqueue
Proxy Design Patterns
2022-08-06 17:17:39 -07:00
Kunwar
7dde075b58 Flyweight Design Patterns 2022-07-31 22:19:32 +05:30
Kunwar
f8310a25ac Proxy Design Patterns 2022-07-23 16:36:12 +05:30
javadevjournal
0165d0d8bc Merge pull request #56 from KunwarVikas/stackandqueue
Java Design Patterns
2022-05-21 17:28:12 -07:00
Kunwar
c83d39750b Java Design Patterns 2022-04-17 13:05:10 +05:30
Kunwar
03b7e798e9 Java Design Patterns 2022-04-09 21:20:17 +05:30
Kunwar
cf9f87e82f Java Design Patterns 2022-04-03 12:02:14 +05:30
81 changed files with 1956 additions and 2 deletions

View File

@@ -47,7 +47,7 @@ public class CustomerService {
customers.sort(Comparator.comparingInt(Customer::getAge));
//pure lambda expression
Collections.sort(customers, (c1, c2) -> c1.getAge() - c1.getAge()); //we careful when using this as it can cause overflow
Collections.sort(customers, (c1, c2) -> c1.getAge() - c2.getAge()); //we careful when using this as it can cause overflow
}
private static List<Customer> getCustomers(){

View File

@@ -0,0 +1,34 @@
import java.util.*;
public class JavaAccessModifiers {
public static void main(String[] args) {
javaInstanceOfOperator();
}
public int myVariable = 10;
public void myMethod() {
// method code here
}
private int myVariable = 10;
private void myMethod() {
// method code here
}
protected int myVariable = 10;
protected void myMethod() {
// method code here
}
int myVariable = 10;
void myMethod() {
// method code here
}
}

View File

@@ -0,0 +1,71 @@
import java.util.*;
public class JavaConstructor {
public class Car {
private String make;
private String model;
private int year;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
}
public class BankAccount {
private String accountNumber;
private String accountHolder;
private double balance;
public BankAccount(String accountNumber, String accountHolder, double balance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = balance;
}
public String getAccountNumber() {
return accountNumber;
}
public String getAccountHolder() {
return accountHolder;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println(amount + " deposited to account " + accountNumber);
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println(amount + " withdrawn from account " + accountNumber);
} else {
System.out.println("Insufficient balance");
}
}
}
}

View File

@@ -0,0 +1,85 @@
import java.util.*;
public class JavaConstructor {
public static void main(String[] args) {
javaInstanceOfOperator();
}
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Person {
private String name;
private int age;
public Person() {
this.name = null;
this.age = 0;
}
}
public class Person {
private String name;
private int age;
public Person() {
this.name = "John Doe";
this.age = 30;
}
}
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Person {
private String name;
private int age;
public Person() {
this("John Doe", 30);
}
public Person(String name) {
this(name, 30);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}
}

View File

@@ -0,0 +1,26 @@
import java.util.*;
public class JavaContinue {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
if (i == 5) {
break;
}
System.out.println(i);
i++;
}
}
public static void breakExample(String[] args) {
int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
outer: for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
if (numbers[i][j] == 5) {
System.out.println("Found 5 at index [" + i + "][" + j + "]");
break outer;
}
}
}
}
}

View File

@@ -0,0 +1,42 @@
import java.util.*;
public class JavaFinal {
public static void main(String[] args) {
javaInstanceOfOperator();
}
public static void javaInstanceOfOperator() {
String str = "Hello, World!";
boolean result = str instanceof String;
System.out.println(result);
}
class Animal {}
class Dog extends Animal {}
public void checkInstance() {
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
System.out.println("Woof!");
}
}
public void javaInstanceOfInterface() {
Thread thread = new Thread();
if (thread instanceof Runnable) {
System.out.println("Thread implements Runnable");
}
}
public void typeCastingWithInstanceOf() {
Object animal = new Cat();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark();
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
cat.meow();
}
}
}

View File

@@ -0,0 +1,25 @@
import java.util.*;
public class JavaThisKeyword {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return super.add(a, b) + c;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
int result1 = calc.add(2, 3);
double result2 = calc.add(2.5, 3.5);
System.out.println(result1);
System.out.println(result2);
}
}

View File

@@ -0,0 +1,36 @@
import java.util.*;
public class JavaAccessModifiers {
public static void main(String[] args) {
javaInstanceOfOperator();
printHello();
int sum = add(2, 3);
boolean result = isPositive(-5);
}
public void printHello() {
System.out.println("Hello");
}
public int add(int a, int b) {
return a + b;
}
public boolean isPositive(int num) {
return num > 0;
}
public int add(int a, int b) {
return a + b;
}
public boolean isPositive(int num) {
return num > 0;
}
}

View File

@@ -0,0 +1,52 @@
import java.util.*;
public class JavaThisKeyword {
public static void main(String[] args) {
javaInstanceOfOperator();
}
public class User {
private String username;
public User(String username) {
setUsername(username);
}
public void setUsername(String username) {
this.username = username;
}
}
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public void printName(String localName) {
System.out.println("Local variable name: " + localName);
System.out.println("Instance variable name: " + this.name);
}
}
public class UserProfile {
private String username;
private int userAge;
public UserProfile() {
this("John Doe", 30);
}
public UserProfile(String name) {
this(name, 30);
}
public UserProfile(String name, int age) {
this.username = name;
this.userAge = age;
}
}
}

View File

@@ -0,0 +1,26 @@
import java.util.*;
public class JavaContinue {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
if (i == 5) {
break;
}
System.out.println(i);
i++;
}
}
public static void breakExample(String[] args) {
int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
outer: for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
if (numbers[i][j] == 5) {
System.out.println("Found 5 at index [" + i + "][" + j + "]");
break outer;
}
}
}
}
}

View File

@@ -0,0 +1,29 @@
import java.util.*;
public class JavaContinue {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if (j == 5) {
continue;
}
System.out.print(i * j + " ");
}
System.out.println();
}
}
public static void continueExample(String[] args) {
outer: for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if (j == 5) {
continue outer;
}
System.out.print(i * j + " ");
}
System.out.println();
}
}
}

View File

@@ -0,0 +1,20 @@
import java.util.*;
public class JavaForEachLoop {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
public static void doWhile() {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
}
}

View File

@@ -0,0 +1,23 @@
import java.util.*;
public class JavaForEachLoop {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Bob");
for (String name : names) {
System.out.println(name);
}
}
public static void forEachLoop(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("John", 25);
ages.put("Jane", 30);
ages.put("Bob", 35);
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + " is " + entry.getValue() + " years old.");
}
}
}

View File

@@ -0,0 +1,21 @@
import java.util.*;
public class JavaForEachLoop {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += i+1;
}
System.out.println("The sum of numbers from 1 to 10 is: " + sum);
}
public static void forLoop(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}

View File

@@ -0,0 +1,21 @@
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JavaIfElse {
public static void main(String[] args) {
int age = 20;
if (age < 18) {
System.out.println("You are not an adult.");
} else {
System.out.println("You are an adult.");
}
}
public static void ifStatement(String[] args) {
int age = 30;
if (age >= 18) {
System.out.println("You are an adult.");
}
}
}

View File

@@ -0,0 +1,28 @@
import java.util.*;
public class JavaContinue {
public static void main(String[] args) {
String str1 = "Hello, World!";
String str2 = new String("Hello, World!");
}
public static void stringPool() {
String str1 = "Hello, World!";
String str2 = "Hello, World!";
}
public static void accessingStringData(String[] args) {
String str = "Hello, World!";
char firstChar = str.charAt(0);
}
public static void manipulateString(String[] args) {
String str1 = "Hello, ";
String str2 = "World!";
String result = str1 + str2;
String str = "Hello, World!";
String upperCaseStr = str.toUpperCase();
String lowerCaseStr = str.toLowerCase();
}
}

View File

@@ -0,0 +1,52 @@
import java.util.*;
public class JavaContinue {
public static void main(String[] args) {
String str = "Welcome To Javadevjournal!";
int length = str.length();
System.out.println("The length of the string is: " + length);
}
public static void javaMethods() {
// Using string literals
String myString = "Hello, World!";
// Using the new keyword
String myString = new String("Hello, World!");
// Using the valueOf() method
int myInt = 42;
String myString = String.valueOf(myInt);
// Using StringBuilder or StringBuffer
StringBuilder builder = new StringBuilder();
builder.append("Hello");
builder.append(", ");
builder.append("World!");
String myString = builder.toString();
}
public static void charAtExample(String[] args) {
String str = "Welcome To Javadevjournal!";
char ch = str.charAt(1);
System.out.println("The character at index 1 is: " + ch);
}
public static void substringExample(String[] args) {
String str = "Welcome To Javadevjournal!";
String subStr = str.substring(11, 24);
System.out.println("The substring is: " + subStr);
}
public static void indexOfExample(String[] args) {
String str = "Welcome to Javadevjournal";
int index = str.indexOf("o");
System.out.println("The index of the first 'o' is: " + index);
}
public static void replaceMethod(String[] args) {
String str = "Welcome to Javadevjournal!";
String newStr = str.replace("o", "0");
System.out.println("The new string is: " + newStr);
}
}

View File

@@ -0,0 +1,47 @@
import java.util.*;
import java.time.DayOfWeek;
public class JavaSwitchStatement {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}
}
public static void switchExample(String[] args) {
DayOfWeek today = DayOfWeek.SATURDAY;
switch (today) {
case MONDAY:
System.out.println("Today is Monday, time to go back to work.");
break;
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
System.out.println("Today is a weekday, time to work.");
break;
case FRIDAY:
System.out.println("Today is Friday, time to finish up and relax.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Today is the weekend, time to have fun!");
break;
default:
System.out.println("Invalid day of the week.");
break;
}
}
}

View File

@@ -0,0 +1,15 @@
import java.util.*;
public class TernaryOperator {
public static void main(String[] args) {
int x = 10;
int y = (x > 5) ? 100 : 200;
}
public static void nestedTernaryOperator() {
int x = 10;
int y = 20;
int z = (x > 5) ? (y > 10 ? 30 : 40) : 50;
}
}

View File

@@ -8,7 +8,7 @@ Java and Spring development tutorials
- [Spring Boot][Spring Boot]
- [Spring][Spring]
- [Spring MVC][Spring MVC]
- Spring Security
- [Spring Security][Spring Security]
- [REST API][REST API]
- [Shopizer][Shopizer]
@@ -91,6 +91,7 @@ Find the `main` class and run it.
[Spring]: https://www.javadevjournal.com/category/spring/ "Spring"
[Spring Boot]: https://www.javadevjournal.com/category/spring-boot/ "Spring Boot"
[Spring MVC]: https://www.javadevjournal.com/category/spring-mvc/ "Spring MVC"
[Spring Security]: https://www.javadevjournal.com/spring-security-tutorial/ "Spring Security Tutorial"
[REST API]: https://www.javadevjournal.com/category/spring/rest/ "REST API"
[Shopizer]: https://www.javadevjournal.com/category/shopizer/ "Shopizer"
[Spring Core Interview Q/A]: https://www.javadevjournal.com/spring/spring-interview-questions/ "Spring Core Interview Q/A"

View File

@@ -0,0 +1,32 @@
package main.com.kunwar.designpatterns.behavioral.cor;
import java.util.Scanner;
/**
* @author Kunwar Vikas
*/
public class ATMDispenser {
private DispenseChain dispenseChain1;
public ATMDispenser() {
// initialize the chain
this.dispenseChain1 = new Dollar50Dispenser();
DispenseChain dispenseChain2 = new Dollar20Dispenser();
DispenseChain dispenseChain3 = new Dollar10Dispenser();
// set the chain of responsibility
dispenseChain1.setNextChain(dispenseChain2);
dispenseChain2.setNextChain(dispenseChain3);
}
public static void main(String[] args) {
ATMDispenser atmDispenser = new ATMDispenser();
int amount = 0;
System.out.print("Enter amount to dispense: ");
Scanner input = new Scanner(System.in);
amount = input.nextInt();
if (amount % 10 != 0) {
System.out.println("Amount should be in multiple of 10s.");
return;
}
// process the request
atmDispenser.dispenseChain1.dispense(new Currency(amount));
}
}

View File

@@ -0,0 +1,15 @@
package main.com.kunwar.designpatterns.behavioral.cor;
/**
* @author Kunwar Vikas
*/
public class Currency {
private int amount;
public Currency(int amount){
this.amount=amount;
}
public int getAmount(){
return this.amount;
}
}

View File

@@ -0,0 +1,9 @@
package main.com.kunwar.designpatterns.behavioral.cor;
/**
* @author Kunwar Vikas
*/
public interface DispenseChain {
void setNextChain(DispenseChain nextChain);
void dispense(Currency currency);
}

View File

@@ -0,0 +1,26 @@
package main.com.kunwar.designpatterns.behavioral.cor;
/**
* @author Kunwar Vikas
*/
public class Dollar10Dispenser implements DispenseChain {
private DispenseChain dispenseChain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.dispenseChain =nextChain;
}
@Override
public void dispense(Currency currency) {
if(currency.getAmount() >= 10){
int num = currency.getAmount()/10;
int remainder = currency.getAmount() % 10;
System.out.println("Dispensing "+num+" 10$ note");
if(remainder !=0) this.dispenseChain.dispense(new Currency(remainder));
}else{
this.dispenseChain.dispense(currency);
}
}
}

View File

@@ -0,0 +1,25 @@
package main.com.kunwar.designpatterns.behavioral.cor;
/**
* @author Kunwar Vikas
*/
public class Dollar20Dispenser implements DispenseChain {
private DispenseChain dispenseChain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.dispenseChain = nextChain;
}
@Override
public void dispense(Currency currency) {
if (currency.getAmount() >= 20) {
int num = currency.getAmount() / 20;
int remainder = currency.getAmount() % 20;
System.out.println("Dispensing " + num + " 20$ note");
if (remainder != 0) this.dispenseChain.dispense(new Currency(remainder));
} else {
this.dispenseChain.dispense(currency);
}
}
}

View File

@@ -0,0 +1,24 @@
package main.com.kunwar.designpatterns.behavioral.cor;
/**
* @author Kunwar Vikas
*/
public class Dollar50Dispenser implements DispenseChain {
private DispenseChain dispenseChain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.dispenseChain =nextChain;
}
@Override
public void dispense(Currency currency) {
if(currency.getAmount() >= 50){
int num = currency.getAmount()/50;
int remainder = currency.getAmount() % 50;
System.out.println("Dispensing "+num+" 50$ note");
if(remainder !=0) this.dispenseChain.dispense(new Currency(remainder));
}else{
this.dispenseChain.dispense(currency);
}
}
}

View File

@@ -0,0 +1,8 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public class FirstSubscriber implements IObserver {
@Override
public void update(Update m) {
System.out.println("MessageSubscriberOne :: " + m.getMessageContent());
}
}

View File

@@ -0,0 +1,5 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public interface IObserver {
public void update(Update m);
}

View File

@@ -0,0 +1,7 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public interface ISubject {
public void attach(IObserver o);
public void detach(IObserver o);
public void notifyUpdate(Update m);
}

View File

@@ -0,0 +1,28 @@
package main.com.kunwar.designpatterns.behavioral.observer;
import java.util.ArrayList;
import java.util.List;
public class MessagePublisher implements ISubject {
private List<IObserver> observers = new ArrayList<>();
////in multithreaded environment, please use thread-safe collections
@Override
public void attach(IObserver o) {
observers.add(o);
}
//in multithreaded environment, please use thread-safe collections
@Override
public void detach(IObserver o) {
observers.remove(o);
}
@Override
public void notifyUpdate(Update m) {
for(IObserver o: observers) {
o.update(m);
}
}
}

View File

@@ -0,0 +1,22 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public class ObserverPatternDemo {
public static void main(String[] args) {
FirstSubscriber firstSubscriber = new FirstSubscriber();
SecondSubscriber secondSubscriber = new SecondSubscriber();
ThirdSubscriber thirdSubscriber = new ThirdSubscriber();
MessagePublisher p = new MessagePublisher();
p.attach(firstSubscriber);
p.attach(secondSubscriber);
p.notifyUpdate(new Update("This is the first update")); //s1 and s2 will receive the update
p.detach(firstSubscriber);
p.attach(thirdSubscriber);
p.notifyUpdate(new Update("This is the second update")); //s2 and s3 will receive the update
}
}

View File

@@ -0,0 +1,8 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public class SecondSubscriber implements IObserver {
@Override
public void update(Update m) {
System.out.println("MessageSubscriberTwo :: " + m.getMessageContent());
}
}

View File

@@ -0,0 +1,8 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public class ThirdSubscriber implements IObserver {
@Override
public void update(Update m) {
System.out.println("MessageSubscriberThree :: " + m.getMessageContent());
}
}

View File

@@ -0,0 +1,13 @@
package main.com.kunwar.designpatterns.behavioral.observer;
public class Update {
final String messageContent;
public Update(String m) {
this.messageContent = m;
}
public String getMessageContent() {
return messageContent;
}
}

View File

@@ -0,0 +1,21 @@
package main.com.kunwar.designpatterns.behavioral.template;
/**
* @author Kunwar
*/
public class Cricket extends Game {
@Override
void endPlay() {System.out.println("Cricket Game Finished!");
}
@Override
void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
}

View File

@@ -0,0 +1,22 @@
package main.com.kunwar.designpatterns.behavioral.template;
/**
* @author Kunwar
*/
public class Football extends Game {
@Override
void endPlay() {
System.out.println("Football Game Finished!");
}
@Override
void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
}

View File

@@ -0,0 +1,20 @@
package main.com.kunwar.designpatterns.behavioral.template;
/**
* @author Kunwar
*/
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//template method
public final void play(){
//initialize the game
initialize();
//start game
startPlay();
//end game
endPlay();
}
}

View File

@@ -0,0 +1,22 @@
package main.com.kunwar.designpatterns.behavioral.template;
/**
* @author Kunwar
*/
public class Hockey extends Game {
@Override
void endPlay() {
System.out.println("Hockey Game Finished!");
}
@Override
void initialize() {
System.out.println("Hockey Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Hockey Game Started. Enjoy the game!");
}
}

View File

@@ -0,0 +1,20 @@
package main.com.kunwar.designpatterns.behavioral.template;
/**
* @author Kunwar
*/
public class TemplatePatternDemo {
public static void main(String[] args) {
Game game = new Cricket();
game.play();
System.out.println();
game = new Football();
game.play();
System.out.println();
game = new Hockey();
game.play();
System.out.println();
game = new Volleyball();
game.play();
}
}

View File

@@ -0,0 +1,22 @@
package main.com.kunwar.designpatterns.behavioral.template;
/**
* @author Kunwar
*/
public class Volleyball extends Game {
@Override
void endPlay() {
System.out.println("Volleyball Game Finished!");
}
@Override
void initialize() {
System.out.println("Volleyball Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Volleyball Game Started. Enjoy the game!");
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.creational.prototype;
/**
* @author Kunwar
*/
public class Circle extends Shape {
public Circle() {
type = "Circle";
}
@Override
public void draw() {
System.out.println("Circle's draw() method.");
}
}

View File

@@ -0,0 +1,19 @@
package javadevjournal.design.creational.prototype;
/**
* @author Kunwar
*/
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
System.out.println("Shape : " + clonedShape3.getType());
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.creational.prototype;
/**
* @author Kunwar
*/
public class Rectangle extends Shape {
public Rectangle() {
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Rectangle's draw() method.");
}
}

View File

@@ -0,0 +1,39 @@
package javadevjournal.design.creational.prototype;
/**
* @author Kunwar
*/
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Use Object class's Clone() method to do the cloning.
*
* @return
*/
public Object clone() {
Object cloneObject = null;
try {
cloneObject = super.clone();
} catch (CloneNotSupportedException e) {
System.out.println("cloning failed");
e.printStackTrace();
}
return cloneObject;
}
}

View File

@@ -0,0 +1,42 @@
package javadevjournal.design.creational.prototype;
import java.util.HashMap;
import java.util.Map;
/**
* @author Kunwar
*/
public class ShapeCache {
private static Map<String, Shape> shapeMap = new HashMap<String, Shape>();
/**
* Return cloned object of Shape class implementing classes.
*
* @param shapeId
* @return
*/
public static Shape getShape(String shapeId) {
Shape toBeClonedShape = shapeMap.get(shapeId);
return (Shape) toBeClonedShape.clone();
}
/**
* In real-world applications, the loading of details will be from a Database.
* We are using a HaspMap to demonstrate the same behavior.
*/
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(), circle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(), square);
Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(), rectangle);
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.creational.prototype;
/**
* @author Kunwar
*/
public class Square extends Shape {
public Square() {
type = "Square";
}
@Override
public void draw() {
System.out.println("Square's draw() method.");
}
}

View File

@@ -0,0 +1,27 @@
package javadevjournal.design.structural.Bridge;
/**
* @author Kunwar
*/
public class BridgePatternClient {
public static void main(String[] args) {
QuestionFormat questions = new QuestionFormat("Java Programming Language");
questions.question = new JavaQuestions();
questions.display();
questions.previous();
questions.next();
questions.display();
questions.next();
questions.display();
questions.previous();
questions.display();
questions.newOne("What is inheritance? ");
questions.newOne("How many types of inheritance are there in java?");
questions.displayAll();
}
}

View File

@@ -0,0 +1,18 @@
package javadevjournal.design.structural.Bridge;
/**
* @author Kunwar
*/
public interface IQuestion {
public void nextQuestion();
public void previousQuestion();
public void newQuestion(String q);
public void deleteQuestion(String q);
public void displayQuestion();
public void displayAllQuestions();
}

View File

@@ -0,0 +1,59 @@
package javadevjournal.design.structural.Bridge;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kunwar
*/
public class JavaQuestions implements IQuestion {
private List<String> questionsList = new ArrayList<String>();
private int currQuesCounter = 0;
public JavaQuestions() {
questionsList.add("What is class? ");
questionsList.add("What is interface? ");
questionsList.add("What is abstraction? ");
questionsList.add("How multiple polymorphism is achieved in java? ");
questionsList.add("How many types of exception handling are there in java? ");
questionsList.add("Define the keyword final for variable, method, and class in java? ");
questionsList.add("What is abstract class? ");
questionsList.add("What is multi-threading? ");
}
public void nextQuestion() {
if (currQuesCounter <= questionsList.size() - 1) {
currQuesCounter++;
} else {
System.out.println("We are already at the last question");
}
}
public void previousQuestion() {
if (currQuesCounter > 0) {
currQuesCounter--;
} else {
System.out.println("We are already at the first question");
}
}
public void newQuestion(String question) {
questionsList.add(question);
}
public void deleteQuestion(String question) {
questionsList.remove(question);
}
public void displayQuestion() {
System.out.println(questionsList.get(currQuesCounter));
}
public void displayAllQuestions() {
for (String question : questionsList) {
System.out.println(question);
}
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.structural.Bridge;
/**
* @author Kunwar
*/
public class QuestionFormat extends QuestionManager {
public QuestionFormat(String catalog) {
super(catalog);
}
public void displayAll() {
System.out.println("\n---------------------------------------------------------");
super.displayAll();
System.out.println("-----------------------------------------------------------");
}
}

View File

@@ -0,0 +1,38 @@
package javadevjournal.design.structural.Bridge;
/**
* @author Kunwar
*/
public class QuestionManager {
protected IQuestion question;
public String catalog;
public QuestionManager(String catalog) {
this.catalog = catalog;
}
public void next() {
question.nextQuestion();
}
public void previous() {
question.previousQuestion();
}
public void newOne(String quest) {
question.newQuestion(quest);
}
public void delete(String quest) {
question.deleteQuestion(quest);
}
public void display() {
question.displayQuestion();
}
public void displayAll() {
System.out.println("Question Paper: " + catalog);
question.displayAllQuestions();
}
}

View File

@@ -0,0 +1,12 @@
package javadevjournal.design.structural.Composite;
/**
* @author Kunwar
*/
public class Circle implements Shape {
@Override
public void drawShape(String color) {
System.out.println("Drawing Circle with color " + color);
}
}

View File

@@ -0,0 +1,35 @@
package javadevjournal.design.structural.Composite;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kunwar
*/
public class Drawing implements Shape {
private List<Shape> shapesList = new ArrayList<Shape>();
@Override
public void drawShape(String fillColor) {
for (Shape shape : shapesList) {
shape.drawShape(fillColor);
}
}
//adding shape to drawing
public void add(Shape s) {
this.shapesList.add(s);
}
//removing shape from drawing
public void remove(Shape s) {
shapesList.remove(s);
}
//removing all the shapes
public void clear() {
System.out.println("Clearing all the shapes from drawing");
this.shapesList.clear();
}
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.structural.Composite;
/**
* @author Kunwar
*/
public class Rectangle implements Shape {
@Override
public void drawShape(String color) {
System.out.println("Drawing Rectangle with color " + color);
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.structural.Composite;
/**
* @author Kunwar
*/
public interface Shape {
public void drawShape(String fillColor);
}

View File

@@ -0,0 +1,11 @@
package javadevjournal.design.structural.Composite;
/**
* @author Kunwar
*/
public class Square implements Shape {
@Override
public void drawShape(String color) {
System.out.println("Drawing Square with color " + color);
}
}

View File

@@ -0,0 +1,31 @@
package javadevjournal.design.structural.Composite;
/**
* @author Kunwar
*/
public class TestCompositePattern {
public static void main(String[] args) {
Shape triangle = new Triangle();
Shape triangle1 = new Triangle();
Shape circle = new Circle();
Shape square = new Square();
Shape rectangle = new Rectangle();
Drawing drawing = new Drawing();
drawing.add(triangle1);
drawing.add(triangle1);
drawing.add(circle);
drawing.add(square);
drawing.add(rectangle);
drawing.drawShape("Red");
drawing.clear();
drawing.add(triangle);
drawing.add(circle);
drawing.add(square);
drawing.add(rectangle);
drawing.drawShape("Blue");
}
}

View File

@@ -0,0 +1,12 @@
package javadevjournal.design.structural.Composite;
/**
* @author Kunwar
*/
public class Triangle implements Shape {
@Override
public void drawShape(String color) {
System.out.println("Drawing Triangle with color " + color);
}
}

View File

@@ -0,0 +1,12 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public class Circle implements Shape {
@Override
public void drawShape() {
System.out.println("The shape is: Circle");
}
}

View File

@@ -0,0 +1,29 @@
package javadevjournal.design.structural.decorator;// DecoratorPatternDemo.java
/**
* @author Kunwar
*/
public class DecoratorPatternDemo {
public static void main(String[] args) {
// Creating objects of Shape interface
Shape circle = new Circle();
Shape rectangle = new Rectangle();
// Creating objects of decorated classes
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal fill");
circle.drawShape();
System.out.println("Rectangle with normal fill");
rectangle.drawShape();
System.out.println("\nCircle of red fill");
redCircle.drawShape();
System.out.println("\nRectangle of red fill");
redRectangle.drawShape();
}
}

View File

@@ -0,0 +1,12 @@
package javadevjournal.design.structural.decorator;// Class 1
/**
* @author Kunwar
*/
public class Rectangle implements Shape {
@Override
public void drawShape() {
System.out.println("The shape is: Rectangle");
}
}

View File

@@ -0,0 +1,27 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void drawShape() {
decoratedShape.drawShape();
//additional method to change the behavior of the shape object
shapeFill(decoratedShape);
}
/**
* This method will change the behavior of the shape object at runtime.
*
* @param decoratedShape
*/
private void shapeFill(Shape decoratedShape) {
System.out.println("Shape Fill color: Red");
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public interface Shape {
void drawShape();
}

View File

@@ -0,0 +1,19 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public abstract class ShapeDecorator implements Shape {
//protected object of Shape Interface.
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
//calling the drawShape method on decoratedShape
public void drawShape() {
decoratedShape.drawShape();
}
}

View File

@@ -0,0 +1,46 @@
package javadevjournal.design.structural.facade;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author Kunwar
*/
public class FacadePatternClient {
private static int choice;
public static void main(String args[]) throws NumberFormatException, IOException {
do {
System.out.print("========= Mobile Shop ============ \n");
System.out.print("1. IPHONE. \n");
System.out.print("2. SAMSUNG. \n");
System.out.print("3. NOKIA. \n");
System.out.print("4. Exit. \n");
System.out.print("Enter your choice: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(br.readLine());
ShopKeeper shopKeeper = new ShopKeeper();
switch (choice) {
case 1: {
shopKeeper.iphonePhoneSale();
}
break;
case 2: {
shopKeeper.samsungPhoneSale();
}
break;
case 3: {
shopKeeper.nokiaPhoneSale();
}
break;
default: {
System.out.println("Nothing You purchased");
}
return;
}
} while (choice != 4);
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.structural.facade;
/**
* @author Kunwar
*/
public interface IMobileShop {
/**
* Mobile Model Number
*/
public void getMobileModelNumber();
/**
* Mobile Price
*/
public void getMobilePrice();
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.structural.facade;
/**
* @author Kunwar
*/
public class Iphone implements IMobileShop {
@Override
public void getMobileModelNumber() {
System.out.println("The model is: IPhone 13");
}
@Override
public void getMobilePrice() {
System.out.println("The price is: 75000INR ");
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.structural.facade;
/**
* @author Kunwar
*/
public class Nokia implements IMobileShop {
@Override
public void getMobileModelNumber() {
System.out.println("The model is: Nokia 1100");
}
@Override
public void getMobilePrice() {
System.out.println("The price is: 1500INR ");
}
}

View File

@@ -0,0 +1,16 @@
package javadevjournal.design.structural.facade;
/**
* @author Kunwar
*/
public class Samsung implements IMobileShop {
@Override
public void getMobileModelNumber() {
System.out.println("The model is: Galaxy 11");
}
@Override
public void getMobilePrice() {
System.out.println("The price is: 85000INR ");
}
}

View File

@@ -0,0 +1,34 @@
package javadevjournal.design.structural.facade;
/**
* @author Kunwar
*/
public class ShopKeeper {
private IMobileShop iphone;
private IMobileShop samsung;
private IMobileShop nokia;
/**
* no args constructor
*/
public ShopKeeper() {
iphone = new Iphone();
samsung = new Samsung();
nokia = new Nokia();
}
public void iphonePhoneSale() {
iphone.getMobileModelNumber();
iphone.getMobilePrice();
}
public void samsungPhoneSale() {
samsung.getMobileModelNumber();
samsung.getMobilePrice();
}
public void nokiaPhoneSale() {
nokia.getMobileModelNumber();
nokia.getMobilePrice();
}
}

View File

@@ -0,0 +1,10 @@
package javadevjournal.design.structural.flyweight;
/**
*
*/
public interface Brush {
public void setColor(String color);
public void draw(String content);
}

View File

@@ -0,0 +1,55 @@
package javadevjournal.design.structural.flyweight;
import java.util.HashMap;
/**
* @author Kunwar
*/
public class BrushFactory {
private static final HashMap<String, Brush> brushMap = new HashMap<>();
public static Brush getThickBrush(String color) {
String key = color + "-THICK";
Brush brush = brushMap.get(key);
if (brush != null) {
return brush;
} else {
brush = new ThickBrush();
brush.setColor(color);
brushMap.put(key, brush);
}
return brush;
}
public static Brush getThinBrush(String color) {
String key = color + "-THIN";
Brush brush = brushMap.get(key);
if (brush != null) {
return brush;
} else {
brush = new ThinBrush();
brush.setColor(color);
brushMap.put(key, brush);
}
return brush;
}
public static Brush getMediumBrush(String color) {
String key = color + "-MEDIUM";
Brush brush = brushMap.get(key);
if (brush != null) {
return brush;
} else {
brush = new MediumBrush();
brush.setColor(color);
brushMap.put(key, brush);
}
return brush;
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.structural.flyweight;
/**
* @author Kunwar
*/
public enum BrushSize {
THIN, MEDIUM, THICK
}

View File

@@ -0,0 +1,41 @@
package javadevjournal.design.structural.flyweight;
/**
* @author Kunwar
*/
public class FlyweightPatternDemo {
public static void main(String[] args) {
// New thick Red Brush
Brush redThickBrush1 = BrushFactory.getThickBrush("RED");
redThickBrush1.draw("Hello There !!");
// Red Brush is shared
Brush redThickBrush2 = BrushFactory.getThickBrush("RED");
redThickBrush2.draw("Hello There Again !!");
System.out.println("Hashcode: " + redThickBrush1.hashCode());
System.out.println("Hashcode: " + redThickBrush2.hashCode());
// New thin Blue Brush
Brush blueThinBrush1 = BrushFactory.getThinBrush("BLUE"); //created new pen
blueThinBrush1.draw("Hello There !!");
// Blue Brush is shared
Brush blueThinBrush2 = BrushFactory.getThinBrush("BLUE"); //created new pen
blueThinBrush2.draw("Hello There Again!!");
System.out.println("Hashcode: " + blueThinBrush1.hashCode());
System.out.println("Hashcode: " + blueThinBrush2.hashCode());
// New MEDIUM Yellow Brush
Brush yellowThinBrush1 = BrushFactory.getMediumBrush("YELLOW"); //created new pen
yellowThinBrush1.draw("Hello There !!");
// Yellow brush is shared
Brush yellowThinBrush2 = BrushFactory.getMediumBrush("YELLOW"); //created new pen
yellowThinBrush2.draw("Hello There Again!!");
System.out.println("Hashcode: " + yellowThinBrush1.hashCode());
System.out.println("Hashcode: " + yellowThinBrush2.hashCode());
}
}

View File

@@ -0,0 +1,26 @@
package javadevjournal.design.structural.flyweight;
/**
* @author Kunwar
*/
public class MediumBrush implements Brush {
/*
intrinsic state - shareable
*/
final BrushSize brushSize = BrushSize.MEDIUM;
/*
extrinsic state - supplied by client
*/
private String color = null;
public void setColor(String color) {
this.color = color;
}
@Override
public void draw(String content) {
System.out.println("Drawing MEDIUM '" + content + "' in color : " + color);
}
}

View File

@@ -0,0 +1,25 @@
package javadevjournal.design.structural.flyweight;
/**
* @author Kunwar
*/
public class ThickBrush implements Brush {
/*
intrinsic state - shareable
*/
final BrushSize brushSize = BrushSize.THICK;
/*
extrinsic state - supplied by client
*/
private String color = null;
public void setColor(String color) {
this.color = color;
}
@Override
public void draw(String content) {
System.out.println("Drawing THICK '" + content + "' in color : " + color);
}
}

View File

@@ -0,0 +1,26 @@
package javadevjournal.design.structural.flyweight;
/**
* @author Kunwar
*/
public class ThinBrush implements Brush {
/*
intrinsic state - shareable
*/
final BrushSize brushSize = BrushSize.THIN;
/*
extrinsic state - supplied by client
*/
private String color = null;
public void setColor(String color) {
this.color = color;
}
@Override
public void draw(String content) {
System.out.println("Drawing THIN '" + content + "' in color : " + color);
}
}

View File

@@ -0,0 +1,25 @@
package javadevjournal.design.structural.proxy;
/**
* @author Kunwar
*/
public class EmployeeInternetAccess implements InternetAccess {
private String employeeName;
@Override
public void grantInternetAccessToEmployees() {
System.out.println("Internet Access granted for employee: " + employeeName);
}
public EmployeeInternetAccess(String empName) {
this.employeeName = empName;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.structural.proxy;
/**
* @author Kunwar
*/
public interface InternetAccess {
public void grantInternetAccessToEmployees();
}

View File

@@ -0,0 +1,28 @@
package javadevjournal.design.structural.proxy;
/**
* @author Kunwar
*/
public class ProxyEmployeeInternetAccess implements InternetAccess {
private String employeeName;
private EmployeeInternetAccess employeeInternetAccess;
public ProxyEmployeeInternetAccess(String employeeName) {
this.employeeName = employeeName;
}
@Override
public void grantInternetAccessToEmployees() {
if (getRole(employeeName) > 4) {
employeeInternetAccess = new EmployeeInternetAccess(employeeName);
employeeInternetAccess.grantInternetAccessToEmployees();
} else {
System.out.println("No Internet access granted. Your job level is below 5");
}
}
public int getRole(String empName) {
//make a DB call to get the employee role and return it.
return 31;
}
}

View File

@@ -0,0 +1,14 @@
package javadevjournal.design.structural.proxy;
/**
* @author Kunwar
*/
public class ProxyPatternClient {
public static final String EMPLOYEE_NAME = "Aayush Sharma";
public static void main(String[] args) {
InternetAccess internetAccess = new ProxyEmployeeInternetAccess(EMPLOYEE_NAME);
internetAccess.grantInternetAccessToEmployees();
}
}