battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

descriptionJAVA design patterns EmptyJAVA design patterns

more_horiz
l1 : hiding the code :

main :

Code:

package sellerBot;

public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      seller chi = new seller();
      chi.selectCar();
   }

}


car class :

Code:

package sellerBot;

public abstract class Car {
   protected double price, oil;
   String brand;
   public abstract void specs();
   @Override
   public String toString() {
      return "Car [price=" + price + ", oil=" + oil + ", brand=" + brand + "]";
   }
   
   
}

sub class delorean :

Code:

package sellerBot;

public class Delorean extends Car{
   private boolean flaxCapacitor;
   double plutonium;
   
   public Delorean() {
      super.brand = this.getClass().toString();
      super.oil = 5;
      super.price = 50000;
      this.flaxCapacitor = true;
      this.plutonium = 20;
   }
   @Override
   public void specs() {
      // TODO Auto-generated method stub
      System.out.println(this.toString());
   }
   @Override
   public String toString() {
      return super.toString() + " Delorean [flaxCapacitor=" + flaxCapacitor + ", plutonium=" + plutonium + "]";
   }
   

}   

factory class :

Code:

package sellerBot;

import java.util.Scanner;

public class seller {
   private Car selected;
   public void selectCar() {
      Scanner s1 = new Scanner(System.in); // after typing this intelliJ should add the import code anyways
      System.out.println("type car U want ");
      String x = s1.next(); // .next(); to input a string
      switch (x.toLowerCase()) {
      case "delorean":
         selected = new Delorean();
         break;

      default:
         break;
      }
      System.out.println(selected.toString());
   }
}


descriptionJAVA design patterns EmptyRe: JAVA design patterns

more_horiz

observer DB :
observer interface : (right click package explorer add new interface)

Code:

public interface Observer {
   void update(String... str);
}

pt2 : observable interface :

Code:


public interface Observable {
   void addObserver(Observer obs);
   void delObserver(Observer obs);
   void notifyObservers();
}

class that implements observer (equip spell):

Code:


public class Cashier implements Observer{
   public static int trackID=0;
   private int observerID=0;
   private String price1,price2,price3;
   
   public Cashier(Observable obs) {
      obs.addObserver(this);
      this.observerID = ++trackID;
      System.out.println("new observer created " + this.toString());
   }

   @Override
   public void update(String... str) {
      // TODO Auto-generated method stub
      price1 = str[0];
      price2 = str[1];
      price3 = str[2];
      System.out.println(toString());
   }

   @Override
   public String toString() {
      return "Cashier [observerID=" + observerID + ", price1=" + price1 + ", price2=" + price2 + ", price3=" + price3
            + "]";
   }
   

}

class that implements observable (equip spell):

Code:

import java.util.ArrayList;

public class MainCashier implements Observable{
   private String price1,price2,price3; // observer replica, enables summoning the update
   ArrayList<Observer> Cashiers; // the database of observers (the heart of the pattern)
   public  MainCashier() {
      // TODO Auto-generated constructor stub
      Cashiers = new ArrayList<>();
   }
   @Override
   public void addObserver(Observer obs) {
      // TODO Auto-generated method stub
      Cashiers.add(obs);
   }

   @Override
   public void delObserver(Observer obs) {
      // TODO Auto-generated method stub
      Cashiers.remove(obs);
   }

   @Override
   public void notifyObservers() {
      // TODO Auto-generated method stub
      for(Observer obs: Cashiers) {
         obs.update(price1,price2,price3);
      }
   }
   public void setPrice1(String p1) {this.price1=p1;notifyObservers();}
   public void setPrice2(String p2) {this.price2=p2;notifyObservers();}
   public void setPrice3(String p3) {this.price3=p3;notifyObservers();}

}

now the continues observable field spell makes sure any updates to its replica fields(see code comments)
are notified to all objects in the main cashier "DB"
the main class to test drive it:

Code:


public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      MainCashier mainCashier = new MainCashier();
      System.out.println();
      Cashier c1 = new Cashier(mainCashier);
      System.out.println();
      mainCashier.setPrice1("500");
      Cashier c2 = new Cashier(mainCashier);
      System.out.println();
      mainCashier.setPrice2("900");
      Cashier c3 = new Cashier(mainCashier);
      mainCashier.setPrice3("9001");
      System.out.println();
      mainCashier.delObserver(c2);
      System.out.println();
      mainCashier.setPrice2("101");
   }

}

descriptionJAVA design patterns Emptybuilder design pattern JAVA

more_horiz

the following design pattern works like naruto kage bunshin. the nested pcbuilder bunshin is a replica class that gets all the needed data
for the pc class constructor. after the pcbuilder fields are set(see main), his assembler methode passes its data to the pc constructor, which are final
and can be set once only.
the jutsu can be used for graphic objecs and other permanant data field objects.

add class :

Code:

public class PC {
   private final String cpu, gpu;
   private final int ram, ssd, hdd;
   
   private PC(PCBuilder pBuilder) {
      this.cpu = pBuilder.cpu;
      this.gpu = pBuilder.gpu;
      this.ram = pBuilder.ram;
      this.ssd = pBuilder.ssd;
      this.hdd = pBuilder.hdd;   
   }
   
   @Override
   public String toString() {
      return "PC [cpu=" + cpu + ", gpu=" + gpu + ", ram=" + ram + ", ssd=" + ssd + ", hdd=" + hdd + "]";
   }

   static class PCBuilder{
      private String cpu, gpu; // replica
      private int ram, ssd, hdd; // replica
      
      public PCBuilder setCpu(String cpu) {
         this.cpu = cpu;
         return this;
      }
      public PCBuilder setGpu(String gpu) {
         this.gpu = gpu;
         return this;
      }
      public PCBuilder setRam(int ram) {
         this.ram = ram;
         return this;
      }
      public PCBuilder setSsd(int ssd) {
         this.ssd = ssd;
         return this;
      }
      public PCBuilder setHdd(int hdd) {
         this.hdd = hdd;
         return this;
      }
      
      public PC assemble() {
         return new PC(this);
      }
      
   }
}


main

Code:

public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      PC HPpc = new PC.PCBuilder().setCpu("I7 7700K")
            .setGpu("nVidia 1060GTX") // == PCBuilder.setGPU()
            .setRam(5)
            .assemble();
      System.out.println(HPpc);
      
      // Second Option:
      
      PC.PCBuilder pBuilder = new PC.PCBuilder();
      pBuilder.setCpu("I5 lame");
      pBuilder.setGpu("Raedon lame");
      pBuilder.setRam(4); // Oh no.
      pBuilder.setHdd(500); // Don't do it to yourself
      
      PC lenovo = pBuilder.assemble();
      System.out.println(lenovo);
   }

}

descriptionJAVA design patterns Emptyinner classes

more_horiz

inner class, a class beefup henshin power up.
add class :

Code:

public class Dog {
 String dogFood = "Meat";

 public Dog() {
 System.out.println("New Dog Created!");
 
 }
 
 public void printDogFood() {
 System.out.println(dogFood);
 
 }
 
 public class DogHelper{
 String dogName = "Sami";
 public DogHelper() {
 System.out.println("New DogHelper created!");
 }
 
 void printDogName() {
 System.out.println(this.dogName);
 }
 
 }
}

main :

Code:

public class Main {

 public static void main(String[] args) {
 Dog sami = new Dog();
 sami.printDogFood();
 
 Dog.DogHelper dogHelper = sami.new DogHelper(); // summon inner class
 
 dogHelper.printDogName();
 

 }

}

ex 2 :
setting the inner class modifier from public to private makes it usable only to its wrapper class :
add class :

Code:

public class serverManager {
 public serverManager() {
 System.out.println("New ServerManager Created!"); // constructor
 }
 
 public void connect() {
 SSLHandler sHandler = new SSLHandler();
 sHandler.i = 15;
 System.out.println("Establishing connection...");
 System.out.println("Creating SSL Signature...");
 
 System.out.println("Using SSL Signature to make server requests");
 }
 
 
 private class SSLHandler{
 private int i = 5;
 public SSLHandler() {
 System.out.println("New SSLHandler created!");
 }
 }
}

main :

Code:

public class Main {

 public static void main(String[] args) {
 
 serverManager serverManager = new serverManager();
    serverManager.connect();
 }

}


example 2 : the true power of the inner class design pattern :



the class with the inner class :

Code:

public class DeleteMe {
 private String food;
 // private String shit = "shit";
 private InnerClass inner;

 public DeleteMe(String dish) {
 super();
 this.inner = new InnerClass();
 this.food = dish;
 }

 public InnerClass getInner() {
 this.inner.eat();
 return this.inner;
 }

 private void eatFood() {
 System.out.println("I have eaten U, happy ? " + this.food);
 }

 protected class InnerClass {
 public void eat() {
 eatFood();
 }
 }

}


summon from the main class :

Code:

DeleteMe d1 = new DeleteMe("spicy hummus");
 DeleteMe.InnerClass d2 = d1.getInner();
 d2.eat();

descriptionJAVA design patterns Emptyclone pattern

more_horiz
JAVA design patterns 257do2

edo tensei no jutsu
student:
name
age
address
grades

managementSys

students table DB
BackUp DB // Mcode state marker ? working state ?
changed hashset
create changed hashset affected
del student ch2
add grade(student name) ch
avgAll
clone student
saveAll changes (clone STDB to BUDB) clear ch
restore (clone BUDB to STDB) clear ch

the following (mini)project also contains the codes to:
:king:  iterate a dictionary (hashtable)
:farao:  referring to a value in a dictionary using the shallow clone jutsu
:joker:  using deep clone method (see inner class student) by overriding the super class objects clone methode
:queen: a simple save or restore algorithm

add class :

Code:

package edoTensei;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

public class StudentManagementSys {
   // Student Data Base :
   Hashtable<String, Student> SDB = new Hashtable<>();
   // BackUpDataBase :
   Hashtable<String, Student> BUDB = new Hashtable<>();
   HashSet<String> changedKeys = new HashSet<>();
   HashSet<String> deleteddKeys = new HashSet<>();
   public void createStudent(String name, String address, int age) {
      SDB.put(name, new Student(name, address, age));
      changedKeys.add(name);
   }
   public void delStudent(String name) {
      if(!SDB.containsKey(name)) {SDB.remove(name);deleteddKeys.add(name);
      changedKeys.remove(name);
      }
      
   }
   public void addGrade(String name, int grade) {
      if(SDB.containsKey(name)) {Student temp = SDB.get(name);temp.addGrade(grade);}//shallow copy jutsu
   }
   public double getAvg() {
      int sum = 0;
      int counter = 0;
      Set<String> setOfStudents = SDB.keySet();
      for(String key : setOfStudents) {
          Student shallowStudent = SDB.get(key);
          for (int x : shallowStudent.grades) {
            sum += x;
            counter ++;
         }
        }
      return (double)sum / (double)counter;
   }
   public void saveAll() {
      // pukhamize SDB to BUBD
      for (String string : deleteddKeys) {
         BUDB.remove(string);
      }
      for (String string : changedKeys) {
         BUDB.put(string, SDB.get(string).clone());
      }
      deleteddKeys.clear();
      changedKeys.clear();
   }
   public void restore() {
      // pukhamize BUBD to SDB
      for (String string : deleteddKeys) {
         SDB.put(string, BUDB.get(string).clone());
      }
      for (String string : changedKeys) {
         SDB.put(string, BUDB.get(string).clone());
      }
      deleteddKeys.clear();
      changedKeys.clear();
   }
   public class Student implements Cloneable{
      private String name,address;
      private int age;
      private List<Integer> grades = new ArrayList<>();
      public Student(String name, String address, int age) {
         super();
         this.name = name;
         this.address = address;
         this.age = age;
      }
      private Student(List<Integer> l1, String name, String address, int age) {
         this.grades = new ArrayList<>();
         this.grades.addAll(l1);
         this.name = name;
         this.address = address;
         this.age = age;
         
      }
      public String getName() {
         return name;
      }
      public void setName(String name) {
         this.name = name;
      }
      public String getAddress() {
         return address;
      }
      public void setAddress(String address) {
         this.address = address;
      }
      public int getAge() {
         return age;
      }
      public void setAge(int age) {
         this.age = age;
      }
      public void addGrade(int grade) {
         grades.add(grade);
      }
      @Override
      protected Student clone() {
         // TODO Auto-generated method stub
         return new Student(this.grades, this.name, this.address, this.age);
      }
   }
}

}


main class :

Code:

package edoTensei;

public class Main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 StudentManagementSys studentManagementSys = new StudentManagementSys();
 studentManagementSys.createStudent("goku", "earth", 30);
 studentManagementSys.addGrade("goku", 90);
 studentManagementSys.addGrade("goku", 70);
 studentManagementSys.createStudent("vegita", "saiyansei", 30);
 studentManagementSys.addGrade("vegita", 90);
 studentManagementSys.addGrade("vegita", 100);
 System.out.println(studentManagementSys.getAvg());
 studentManagementSys.saveAll();
 
 }

}

which is the design pattern.

descriptionJAVA design patterns Emptydecorator programmatic design pattern

more_horiz
JAVA design patterns 25xibt

input stream gets char input at a time :

Code:

package input.console;

import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamReaderExample {

 public static void main(String[] args) throws IOException {
 InputStreamReader isr = new InputStreamReader(System.in);
 int userInput = isr.read();
 while(userInput != -1) {
 char userChar = (char) userInput;
 System.out.print(userChar + " ");
 userInput = isr.read();
 }
 }

}


its decorator class notice the close methode changed to do nothing :

Code:


package input.console;

import java.io.IOException;
import java.io.InputStream;


public class InputStreamDecorator extends InputStream {
InputStream is;
boolean canClose = false;

public InputStreamDecorator(InputStream is) {
this.is = is;
}

@Override
public int read() throws IOException {
// TODO Auto-generated method stub
return is.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return is.read(b, off, len);
}
@Override
public int read(byte[] b) throws IOException {
// TODO Auto-generated method stub
return is.read(b);
}
@Override
public synchronized void reset() throws IOException {
// TODO Auto-generated method stub
is.reset();
}
@Override
public int available() throws IOException {
// TODO Auto-generated method stub
return is.available();
}
@Override
public long skip(long n) throws IOException {
// TODO Auto-generated method stub
return is.skip(n);
}
@Override
public void close() throws IOException {
if(canClose) {
is.close();
}
}

}

the decorator enables antiGlitching the following code
that closes the scanner in this main class:

Code:

package input.console;

import java.io.IOException;
import java.util.Scanner;

public class CustomIn {

 public static void main(String[] args) throws IOException {
 InputStreamDecorator isd = new InputStreamDecorator(System.in);
 System.setIn(isd);
 
 Scanner s1 = new Scanner(System.in);
 s1.next();
 s1.close();
 
 //isd.canClose = true;
 
 Scanner s2 = new Scanner(System.in);
 s2.next();
 s2.close();
 
 Scanner s3 = new Scanner(System.in);
 s3.next();
 
 }

}


2nd example :
bufferedreader :

Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

 public static void main(String[] args) throws IOException {
 List<String> filecontent = new ArrayList<>();
 String filePath ="C:\\Users\\Lenovo\\Desktop\\HW\\ex.txt";
 try (BufferedReader bReader = new BufferedReader(new FileReader(filePath))){
 String line;
 while((line = bReader.readLine())!=null ){
 if(!line.trim().equals("")) {filecontent.add(line + "\n");}
 }
 } catch (Exception e) {
 // TODO: handle exception
 System.err.println("exception occured");
 }
 System.out.println(filecontent);
 }
}


bufferedReader decorator :

Code:

package input.console;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CustomBR {
 private BufferedReader br;
 
 public CustomBR() {
 System.setIn(new InputStreamDecorator(System.in));
 br = new BufferedReader(new InputStreamReader(System.in));
 }
 
 public int readInt() throws NumberFormatException, IOException {
 return Integer.parseInt(br.readLine());
 }
 public double readDouble() throws NumberFormatException, IOException {
 return Double.parseDouble(br.readLine());
 }
 public String read() throws NumberFormatException, IOException {
 return br.readLine();
 }
 public boolean readBool() throws NumberFormatException, IOException {
 return Boolean.parseBoolean(br.readLine());
 }
 public void close() throws IOException {
 br.close();
 }
 
}

descriptionJAVA design patterns Emptyadapter pattern

more_horiz



:rlx:

descriptionJAVA design patterns EmptyRe: JAVA design patterns

more_horiz
Simply put, a facade encapsulates a complex subsystem behind a simple interface. It hides much of the complexity and makes the subsystem easy to use.
Also, if we need to use the complex subsystem directly, we still can do that; we aren’t forced to use the facade all the time.

java example :

Code:

public class CarEngineFacade {
    private static int DEFAULT_COOLING_TEMP = 90;
    private static int MAX_ALLOWED_TEMP = 50;
    private FuelInjector fuelInjector = new FuelInjector();
    private AirFlowController airFlowController = new AirFlowController();
    private Starter starter = new Starter();
    private CoolingController coolingController = new CoolingController();
    private CatalyticConverter catalyticConverter = new CatalyticConverter();
 
    public void startEngine() {
        fuelInjector.on();
        airFlowController.takeAir();
        fuelInjector.on();
        fuelInjector.inject();
        starter.start();
        coolingController.setTemperatureUpperLimit(DEFAULT_COOLING_TEMP);
        coolingController.run();
        catalyticConverter.on();
    }
 
    public void stopEngine() {
        fuelInjector.off();
        catalyticConverter.off();
        coolingController.cool(MAX_ALLOWED_TEMP);
        coolingController.stop();
        airFlowController.off();
    }


to start the car :

facade.startEngine();
// ...
facade.stopEngine();


façade is just like using an interface without the obligation to rewrite the requiped methodes

of said interface.

:hisatsu:

descriptionJAVA design patterns Emptycomplete list of design patterns for programmers

more_horiz
Abstract factory
Adapter
Builder
Chain of responsibilit
Command
Composit
Decorator
Facade
Factory Method
Flyweigh
Interpreter
LivinGrimoire :grimoire:
Mediator
Memento
Observe
Prototype
Proxy
Singleton
State
Strategy
Template Method
Visitor
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply