logo

Singleton dizajn obrazac u Javi

  1. Singleton dizajn obrazac u Javi
  2. Prednost Singleton uzorka
  3. Upotreba Singleton obrasca
  4. Primjer Singleton obrasca

Singleton Pattern kaže da samo 'definirati klasu koja ima samo jednu instancu i pruža joj globalnu točku pristupa'.

Drugim riječima, klasa mora osigurati da se stvori samo jedna instanca i da se jedan objekt može koristiti u svim ostalim klasama.

Postoje dva oblika singleton dizajn uzorka

  • Rana instancija: stvaranje instance u vrijeme učitavanja.
  • Lijena instancija: stvaranje instance kada je potrebno.

Prednost Singleton uzorka dizajna

  • Štedi memoriju jer se objekt ne stvara na svaki zahtjev. Samo se pojedinačna instanca ponovno i ponovno koristi.

Korištenje uzorka dizajna Singleton

  • Singleton uzorak se uglavnom koristi u aplikacijama s više niti i bazama podataka. Koristi se za bilježenje, predmemoriju, skupove niti, konfiguracijske postavke itd.

Uml uzorka dizajna Singleton


Kako stvoriti Singleton dizajn uzorak?

Da bismo stvorili klasu singleton, moramo imati statički član klase, privatni konstruktor i statičku tvorničku metodu.

  • Statički član: Memoriju dobiva samo jednom zbog statike, sadrži instancu klase Singleton.
  • Privatni graditelj: To će spriječiti instanciranje klase Singleton izvan klase.
  • Statička tvornička metoda: Ovo osigurava globalnu točku pristupa objektu Singleton i vraća instancu pozivatelju.

Razumijevanje rane instancije Singleton uzorka

U tom slučaju, stvaramo instancu klase u trenutku deklariranja člana statičkih podataka, tako da se instanca klase kreira u vrijeme učitavanja klase.

Pogledajmo primjer singleton dizajn uzorka koji koristi ranu instanciju.

Datoteka: A.java
 class A{ private static A obj=new A();//Early, instance will be created at load time private A(){} public static A getA(){ return obj; } public void doSomething(){ //write your code } } 

Razumijevanje lijene instancije Singleton uzorka

U tom slučaju stvaramo instancu klase u sinkroniziranoj metodi ili sinkroniziranom bloku, tako da se instanca klase kreira kada je potrebno.

Pogledajmo jednostavan primjer singleton dizajn uzorka koji koristi lijeno instanciranje.

Datoteka: A.java
 class A{ private static A obj; private A(){} public static A getA(){ if (obj == null){ synchronized(Singleton.class){ if (obj == null){ obj = new Singleton();//instance will be created at request time } } } return obj; } public void doSomething(){ //write your code } } 

Značenje Classloadera u Singleton uzorku

Ako klasu singleton učitavaju dva učitavača klasa, stvorit će se dvije instance klase singleton, po jedna za svaki učitavač klasa.


Značaj serijalizacije u Singleton uzorku

Ako je klasa singleton Serializable, možete serijalizirati instancu singletona. Nakon što je serijaliziran, možete ga deserijalizirati, ali neće vratiti singleton objekt.

piton zmija protiv anakonde

Da biste riješili ovaj problem, morate nadjačati metodu readResolve(). koji provodi singleton. Poziva se odmah nakon deserijalizacije objekta. Vraća singleton objekt.

 public class A implements Serializable { //your code of singleton protected Object readResolve() { return getA(); } } 

Razumijevanje stvarnog primjera Singleton uzorka

  • Napravit ćemo klasu JDBCSingleton. Ova klasa JDBCSingleton sadrži svoj konstruktor kao privatni i svoju privatnu statičku instancu jdbc.
  • Klasa JDBCSingleton pruža statičku metodu za prijenos svoje statičke instance vanjskom svijetu. Sada će klasa JDBCSingletonDemo koristiti klasu JDBCSingleton za dobivanje objekta JDBCSingleton.

Pretpostavka: stvorili ste tablicu userdata koja ima tri polja uid, uname i upassword u bazi podataka mysql. Ime baze podataka je ashwinirajput, korisničko ime je root, lozinka je ashwini.

Datoteka: JDBCSingleton.java
 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; class JDBCSingleton { //Step 1 // create a JDBCSingleton class. //static member holds only one instance of the JDBCSingleton class. private static JDBCSingleton jdbc; //JDBCSingleton prevents the instantiation from any other class. private JDBCSingleton() { } //Now we are providing gloabal point of access. public static JDBCSingleton getInstance() { if (jdbc==null) { jdbc=new JDBCSingleton(); } return jdbc; } // to get the connection from methods like insert, view etc. private static Connection getConnection()throws ClassNotFoundException, SQLException { Connection con=null; Class.forName('com.mysql.jdbc.Driver'); con= DriverManager.getConnection('jdbc:mysql://localhost:3306/ashwanirajput', 'root', 'ashwani'); return con; } //to insert the record into the database public int insert(String name, String pass) throws SQLException { Connection c=null; PreparedStatement ps=null; int recordCounter=0; try { c=this.getConnection(); ps=c.prepareStatement('insert into userdata(uname,upassword)values(?,?)'); ps.setString(1, name); ps.setString(2, pass); recordCounter=ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ if (ps!=null){ ps.close(); }if(c!=null){ c.close(); } } return recordCounter; } //to view the data from the database public void view(String name) throws SQLException { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con=this.getConnection(); ps=con.prepareStatement('select * from userdata where uname=?'); ps.setString(1, name); rs=ps.executeQuery(); while (rs.next()) { System.out.println('Name= '+rs.getString(2)+'	'+'Paasword= '+rs.getString(3)); } } catch (Exception e) { System.out.println(e);} finally{ if(rs!=null){ rs.close(); }if (ps!=null){ ps.close(); }if(con!=null){ con.close(); } } } // to update the password for the given username public int update(String name, String password) throws SQLException { Connection c=null; PreparedStatement ps=null; int recordCounter=0; try { c=this.getConnection(); ps=c.prepareStatement(' update userdata set upassword=? where uname=''+name+'' '); ps.setString(1, password); recordCounter=ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ if (ps!=null){ ps.close(); }if(c!=null){ c.close(); } } return recordCounter; } // to delete the data from the database public int delete(int userid) throws SQLException{ Connection c=null; PreparedStatement ps=null; int recordCounter=0; try { c=this.getConnection(); ps=c.prepareStatement(' delete from userdata where uid=''+userid+'' '); recordCounter=ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally{ if (ps!=null){ ps.close(); }if(c!=null){ c.close(); } } return recordCounter; } }// End of JDBCSingleton class 
Datoteka: JDBCSingletonDemo.java
 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; class JDBCSingletonDemo{ static int count=1; static int choice; public static void main(String[] args) throws IOException { JDBCSingleton jdbc= JDBCSingleton.getInstance(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); do{ System.out.println('DATABASE OPERATIONS'); System.out.println(' --------------------- '); System.out.println(' 1. Insertion '); System.out.println(' 2. View '); System.out.println(' 3. Delete '); System.out.println(' 4. Update '); System.out.println(' 5. Exit '); System.out.print('
'); System.out.print('Please enter the choice what you want to perform in the database: '); choice=Integer.parseInt(br.readLine()); switch(choice) { case 1:{ System.out.print('Enter the username you want to insert data into the database: '); String username=br.readLine(); System.out.print('Enter the password you want to insert data into the database: '); String password=br.readLine(); try { int i= jdbc.insert(username, password); if (i>0) { System.out.println((count++) + ' Data has been inserted successfully'); }else{ System.out.println('Data has not been inserted '); } } catch (Exception e) { System.out.println(e); } System.out.println('Press Enter key to continue...'); System.in.read(); }//End of case 1 break; case 2:{ System.out.print('Enter the username : '); String username=br.readLine(); try { jdbc.view(username); } catch (Exception e) { System.out.println(e); } System.out.println('Press Enter key to continue...'); System.in.read(); }//End of case 2 break; case 3:{ System.out.print('Enter the userid, you want to delete: '); int userid=Integer.parseInt(br.readLine()); try { int i= jdbc.delete(userid); if (i>0) { System.out.println((count++) + ' Data has been deleted successfully'); }else{ System.out.println('Data has not been deleted'); } } catch (Exception e) { System.out.println(e); } System.out.println('Press Enter key to continue...'); System.in.read(); }//End of case 3 break; case 4:{ System.out.print('Enter the username, you want to update: '); String username=br.readLine(); System.out.print('Enter the new password '); String password=br.readLine(); try { int i= jdbc.update(username, password); if (i>0) { System.out.println((count++) + ' Data has been updated successfully'); } } catch (Exception e) { System.out.println(e); } System.out.println('Press Enter key to continue...'); System.in.read(); }// end of case 4 break; default: return; } } while (choice!=4); } } 

preuzmite ovaj primjer Singleton uzorka

Izlaz