battle programminga forum for elite programmerswith extreme will powerto sharpen theire skills
 
HomeCalendarFAQSearchMemberlistUsergroupsRegisterLog in
Share | 
 

 JAVA design patterns

Go down 
AuthorMessage
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: JAVA design patterns   Tue Feb 13, 2018 8:19 pm

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());
   }
}


_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: Re: JAVA design patterns   Wed Feb 14, 2018 10:03 pm


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");
   }

}

_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: builder design pattern JAVA   Mon Feb 19, 2018 9:07 am


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);
   }

}

_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: inner classes   Mon Feb 19, 2018 1:09 pm


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();
   }

}

_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: clone pattern   Sat Feb 24, 2018 8:57 am



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
jocolor  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.

_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: decorator programmatic design pattern   Wed Mar 07, 2018 9:53 pm



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();
 }
 
}

_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: adapter pattern   Mon Sep 10, 2018 11:52 pm




relaxation


_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
 
JAVA design patterns
Back to top 
Page 1 of 1
 Similar topics
-
» Verify command when used with Java,JUNIT and Eclipse
» opera browser not loading the page using selenium Rc(Java)
» How to design UI testing using selenium 2
» JAVA tunnel Based UAE Solution Available in Just $149 @ VoIP
» [Help] Java input Username field as a timestamp

Permissions in this forum:You cannot reply to topics in this forum
battle programmers alliance :: battle programming alliance :: chit chat-
Jump to: