logo

Viena dizaina modelis Java valodā

  1. Viena dizaina modelis Java valodā
  2. Singleton Pattern priekšrocības
  3. Singleton Pattern izmantošana
  4. Singleton modeļa piemērs

Singleton Pattern saka, ka tikai 'definēt klasi, kurai ir tikai viena instance un kas nodrošina tai globālu piekļuves punktu'.

Citiem vārdiem sakot, klasei ir jānodrošina, lai tiktu izveidota tikai viena instance un vienu objektu var izmantot visas pārējās klases.

Ir divas viengabala dizaina modeļa formas

  • Agrīna instantiācija: instances izveide ielādes laikā.
  • Slinka instancē: gadījuma izveidošana.

Singleton dizaina modeļa priekšrocība

  • Ietaupa atmiņu, jo objekts netiek izveidots pēc katra pieprasījuma. Atkal un atkal tiek izmantots tikai viens gadījums.

Singleton dizaina modeļa izmantošana

  • Singleton modelis galvenokārt tiek izmantots daudzpavedienu un datu bāzu lietojumprogrammās. To izmanto reģistrēšanā, kešatmiņā, pavedienu baseinos, konfigurācijas iestatījumos utt.

Uml Singleton dizaina modelis


Kā izveidot Singleton dizaina modeli?

Lai izveidotu singleton klasi, mums ir nepieciešams statisks klases dalībnieks, privātais konstruktors un statiskā rūpnīcas metode.

  • Statisks dalībnieks: Tas iegūst atmiņu tikai vienu reizi statiskās strāvas dēļ, tajā ir Singleton klases gadījums.
  • Privātais konstruktors: Tas neļaus izveidot Singleton klasi ārpus klases.
  • Statiskā rūpnīcas metode: Tas nodrošina globālo piekļuves punktu Singleton objektam un atgriež gadījumu zvanītājam.

Izpratne par Singleton modeļa agrīnu instantiāciju

Šādā gadījumā mēs izveidojam klases gadījumu statisko datu dalībnieka deklarēšanas laikā, tāpēc klases gadījums tiek izveidots klases ielādes laikā.

Apskatīsim atsevišķa dizaina modeļa piemēru, izmantojot agrīnu instantiāciju.

Fails: 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 } } 

Izpratne par slinko Singleton Pattern instantiation

Šādā gadījumā klases instanci veidojam sinhronizētā metodē vai sinhronizētā blokā, tāpēc klases instancē tiek izveidota nepieciešamība.

Apskatīsim vienkāršu viena dizaina modeļa piemēru, izmantojot slinku instantiāciju.

Fails: 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 } } 

Classloader nozīme Singleton Pattern

Ja viena klase tiek ielādēta ar diviem klases ielādētājiem, tiks izveidotas divas viengabala klases instances, viena katrai klases ielādētājam.


Serializācijas nozīme Singleton Pattern

Ja viena klase ir serializējama, varat serializēt vienreizējo gadījumu. Kad tas ir serializēts, varat to deserializēt, taču tas neatgriezīs viengabala objektu.

tīģera un lauvas atšķirība

Lai atrisinātu šo problēmu, jums ir jāignorē ReadResolve() metode kas ievieš vienu vienību. Tas tiek izsaukts tūlīt pēc objekta deserializācijas. Tas atgriež viengabala objektu.

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

Izpratne par reālu Singleton modeļa piemēru

  • Mēs gatavojamies izveidot JDBCSingleton klasi. Šī JDBCSingleton klase satur savu konstruktoru kā privātu un privātu statisku instanci jdbc.
  • JDBCSingleton klase nodrošina statisku metodi, lai nogādātu savu statisko instanci uz ārpasauli. Tagad JDBCSingletonDemo klase izmantos JDBCSingleton klasi, lai iegūtu JDBCSingleton objektu.

Pieņēmums: esat izveidojis tabulu userdata, kurā ir trīs lauki uid, uname un upassword mysql datu bāzē. Datu bāzes nosaukums ir ashwinirajput, lietotājvārds ir root, parole ir ashwini.

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

lejupielādējiet šo Singleton modeļa piemēru

Izvade