Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.lang.reflect.InvocationTargetException;
- abstract class Singleton {
- private static Singleton instance;
- protected Singleton() {}
- public static Singleton getInstance() {
- if (instance == null) {
- String line = Singleton.getSingletonConfigure();
- try {
- instance = (Singleton)Class.forName("com.design_patterns.singleton." + line)
- .getDeclaredConstructor().newInstance();
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
- | InvocationTargetException | NoSuchMethodException | SecurityException
- | ClassNotFoundException e) {
- System.out.println("Falló la configuración.");
- }
- }
- return instance;
- }
- private static String getSingletonConfigure() {
- BufferedReader in = null;
- String className = "";
- try {
- in = new BufferedReader(new FileReader("singletonConfigure"));
- className = in.readLine();
- } catch (IOException ex) {
- System.out.println("IOException al leer: " + ex.getMessage());
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException ex) {
- System.out.println("IOException al cerrar: "
- + ex.getMessage());
- }
- }
- }
- return className;
- }
- protected abstract void showInstance();
- }
- class ASingleton extends Singleton {
- protected ASingleton() {
- super();
- }
- @Override
- protected void showInstance() {
- System.out.println("ASingleton");
- }
- }
- class BSingleton extends Singleton {
- protected BSingleton() {
- super();
- }
- @Override
- protected void showInstance() {
- System.out.println("BSingleton");
- }
- }
- class Client {
- private static void execute() {
- Singleton.getInstance().showInstance();
- }
- public static void main(String[] args) {
- execute();
- }
- }
Add Comment
Please, Sign In to add comment