Design pattern - SINGLETON by Vi5i0n

ljuskaArchive
//archivePosts: 37Member, Moderator edited December 2016 in Java

Singleton je najjednostavniji design pattern za implementaciju. Spada u grupu kreacionih paterna. Sama klasa ja odgovorna za kreiranje objekta, a klasa takodje omogucava preko staticne metode da se pristupi objektu direktno, bez instanciranja klase.

      public class LjuskaSingle{
        private static LjuskaSingle ljuskaSingle = new LjuskaSingle();

        private LjuskaSingle(){}

        private static LjuskaSingle getInstance(){
            return ljuskaSingle;
       }

        public void prikaziPoruku() {
            System.out.println("Hello world");
        }
    }

Kao sto vidite, potrebno je postaviti da konstruktor bude private, pa se na taj nacin onemogucava instanciranje klase koriscenjem praznog konstruktora.

`LjuskaSingle ljuska = new LjuskaSingle(); // /Compile Time Error: The constructor LjuskaSingle() is not visible`

Koriscenje instance LjuskaSingle:

    LjuskaSingle ljuska = LjuskaSingle.getInstance();
    ljuska.prikaziPoruku(); //Hello World

Source: Ljuska arhiva

Sign In or Register to comment.

Welcome

It looks like you're new here. If you want to get involved, click one of these buttons!

Discussions