The document discusses implementing the singleton pattern to broadcast messages to different types of notice boards in a flexible way. It describes evolving the implementation from a basic singleton to support multiple notice board types by applying principles of abstraction, dependency injection and the factory pattern. This allows creating notice board, broadcaster and messenger objects dynamically based on the board type while maintaining loose coupling between components.
Czym się różnie JMS od AMQP? Co to jest queue? Co to jest topic? Jak zlecać zadania w przyszłości używając kolejek? Jak się do tego podpiąć z Javy? Na te i inne pytania postaram się odpowiedzieć na mojej prezentacji.
Continuing where module 2 left off, this part of the course explains signals and slots in more detail and tells you how to extend functionality of existing widgets by subclassing them. In real applications, widgets are often used in dialogs or inside the main window, which is a container for widgets and by default supports menus, toolbars and actions. These topics are all demonstrated via small examples.
Treinamento de Qt básico apresentado na semanada de tecnologia do Barão de Mauá (Ribeirão Preto/SP) usando um material provido pela Nokia com modificações.
Dart, le nouveau langage Web de Google présenté au public en octobre 2011 a pour objectif de proposer une alternative au JavaScript.
Bien que la version finale ne soit pas encore disponible (pour cela il faudra attendre cet été), Dart est utilisable dès aujourd'hui.
Au cours de cette présentation sont introduits les éléments suivants :
- comment Dart permet de développer des applications clientes aussi bien que serveurs,
- le langage,
- les outils permettant un développement industrialisé et une productivité accrue.
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingLuciano Mammino
Learn how you can use some JavaScript/Node.js black magic to crack JWT tokens and impersonate other users or escalate privileges. Just add a pinch of ZeroMQ, a dose of parallel computing, a 4 leaf clover, mix everything applying some brute force and you'll get a powerful JWT cracking potion!
This document discusses effective practices for dependency injection (DI). It begins with a quick DI refresher and then provides guidelines for DI such as: explicitly defining dependencies, injecting exactly what is needed, preferring constructor injection, avoiding work in constructors, and avoiding direct dependencies on the injector. It also discusses testing code using DI, applying DI to existing code, and techniques for migrating code to use DI such as bottom-up or top-down approaches.
This document compares and contrasts the Observer Pattern and different signal/slot implementations in Qt, Boost, and Synapse. It begins with an overview of the Observer Pattern and its goal of loosely coupling objects. It then provides examples of implementing signals and slots in Qt using QObjects and Q_OBJECT. Next, it discusses how to achieve similar functionality using Boost::signals2. Finally, it briefly introduces the Synapse library as another alternative that allows transferring signal handling between threads.
Czym się różnie JMS od AMQP? Co to jest queue? Co to jest topic? Jak zlecać zadania w przyszłości używając kolejek? Jak się do tego podpiąć z Javy? Na te i inne pytania postaram się odpowiedzieć na mojej prezentacji.
Continuing where module 2 left off, this part of the course explains signals and slots in more detail and tells you how to extend functionality of existing widgets by subclassing them. In real applications, widgets are often used in dialogs or inside the main window, which is a container for widgets and by default supports menus, toolbars and actions. These topics are all demonstrated via small examples.
Treinamento de Qt básico apresentado na semanada de tecnologia do Barão de Mauá (Ribeirão Preto/SP) usando um material provido pela Nokia com modificações.
Dart, le nouveau langage Web de Google présenté au public en octobre 2011 a pour objectif de proposer une alternative au JavaScript.
Bien que la version finale ne soit pas encore disponible (pour cela il faudra attendre cet été), Dart est utilisable dès aujourd'hui.
Au cours de cette présentation sont introduits les éléments suivants :
- comment Dart permet de développer des applications clientes aussi bien que serveurs,
- le langage,
- les outils permettant un développement industrialisé et une productivité accrue.
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingLuciano Mammino
Learn how you can use some JavaScript/Node.js black magic to crack JWT tokens and impersonate other users or escalate privileges. Just add a pinch of ZeroMQ, a dose of parallel computing, a 4 leaf clover, mix everything applying some brute force and you'll get a powerful JWT cracking potion!
This document discusses effective practices for dependency injection (DI). It begins with a quick DI refresher and then provides guidelines for DI such as: explicitly defining dependencies, injecting exactly what is needed, preferring constructor injection, avoiding work in constructors, and avoiding direct dependencies on the injector. It also discusses testing code using DI, applying DI to existing code, and techniques for migrating code to use DI such as bottom-up or top-down approaches.
This document compares and contrasts the Observer Pattern and different signal/slot implementations in Qt, Boost, and Synapse. It begins with an overview of the Observer Pattern and its goal of loosely coupling objects. It then provides examples of implementing signals and slots in Qt using QObjects and Q_OBJECT. Next, it discusses how to achieve similar functionality using Boost::signals2. Finally, it briefly introduces the Synapse library as another alternative that allows transferring signal handling between threads.
This document discusses common concurrency problems in Java and how to address them. It covers issues that can arise from shared mutable data being accessed without proper synchronization between threads, as well as problems related to visibility and atomicity of operations. Specific problems covered include mutable statics, double-checked locking, volatile arrays, and non-atomic operations like incrementing a long. The document provides best practices for locking, wait/notify, thread coordination, and avoiding deadlocks, spin locks, and lock contention.
Qt Quick/QML brings designers and developers together to create and collaborate. QML is a collection of technologies that can build modern and fluid interfaces for applications – quickly. Join us for this webinar to explore the best of QML for mobile, embedded and desktop.
Part IV will cover:
- Dynamic Item Creation
- Keyboard Input Handling
Come hear about the highly available and massively scalable cloud storage service that is provided by Windows Azure. Learn how to create and access the different types of Windows Azure storage available, including blobs, tables, and queues.
The Ring programming language version 1.3 book - Part 7 of 88Mahmoud Samir Fayed
Ring 1.3 includes improvements to RingQt classes, the Objects library, LibCurl, and other features. Better RingQt classes allow getting event information and enabling/disabling events. The updated Objects library manages GUI objects and provides a natural API for creating windows from classes. RingLibCurl adds functions wrapping LibCurl. Other enhancements include better support for calling methods from object attributes, displaying compiler warnings, and code quality improvements.
This presentation and we will explore some of the more complex areas of QML and present tips, tricks, best practices and common areas of error and confusion. The material is based on real-world experience developing customer applications for mobile, embedded and desktop.
Part II covers:
- Anchors
- Creating New Items
- States and Transitions
Local variables are stored in memory during the execution of a function. When the function exits, the memory for local variables is deallocated. Local variables provide convenient temporary storage but have a short lifetime and cannot persist beyond the function call. Returning a pointer to a local variable from a function results in a dangling pointer as the memory is deallocated when the function exits.
O quanto você está satisfeito com o código que produz? Mais ainda: o quanto você está satisfeito como profissional? Na busca pela melhoria de nossas aplicações, caímos num grande desafio: melhorar a nós mesmos!
Numa conversa franca e descontraída, Samuel e Victor tentarão apresentar idéias sobre como você pode melhorar seu próprio trabalho e sentir orgulho do que faz.
This document describes a mobile authentication and key exchange protocol that uses nested one-time secrets. It contains modules for the user, VLR verification, HLR verification, key generation, and nested one-time secrets. The protocol uses lightweight public key cryptography and a challenge-response technique in two stages: an initial procedure and real execution stage. This allows for fast mutual authentication and agreement of a nested one-time secret while providing greater security and lower computational complexity than other wireless authentication schemes.
Example of using Kotlin lang features for writing DSL for Spark-Cassandra connector. Comparison Kotlin lang DSL features with similar features in others JVM languages (Scala, Groovy).
The document contains code for a web service class that connects to a MySQL database and provides various methods for retrieving, updating, and inserting user data. The methods include login authentication, retrieving user account information and transaction history, changing passwords, transferring funds between accounts, and getting the current account balance. The class connects to the database, executes SQL queries, and returns data to the caller.
This document discusses best practices for handling null values in Java. It recommends: failing fast with NullPointerExceptions instead of silently returning null; never returning null values from methods; marking optional parameters and return values with Java's Optional class; using Optional's map and flatMap methods to avoid deep null checks; and using Guava transforms if on Java 6/7 prior to Java 8 streams. The document provides code examples demonstrating these techniques for optional user objects returned from databases and assigned to groups.
The document describes a program for a multi-client chat client-server application using Java graphical programming. It includes the code for the ChatServer class that handles connections from multiple clients and broadcasts messages. It also includes the code for the ChatClient class that allows a client to connect to the server, send and receive messages, and view an online users list. The program allows for real-time text communication between multiple clients connected to a central server.
Behavioral Pattern of the design pattern.
Introducing 6 type patterns and also including the pros and cons. It's easy to understand what's kind of scenario it should be used.
Design pattern part 2 - structural patternJieyi Wu
This is first part: https://www.slideshare.net/JieyiWu1/design-pattern-part-1-81195876
Structural Pattern is introducing 7 type patterns and also including the pros and cons to you.
An Android operating system is an open source Linux-based OS for mobile devices. It includes application building blocks like activities, intents, broadcast receivers and services. To set up the Android development environment, developers need to install the Android SDK, Eclipse IDE, ADT plugin and create an Android virtual device. The document then provides instructions on creating an Android project in Eclipse, understanding the project structure and running an Android application.
This document summarizes a MongoDB live coding session presented by Tobias Trelle. It introduces MongoDB concepts like documents, collections, CRUD operations, queries including geospatial queries, replication, sharding, and the Java and Spring Data APIs. It also advertises MongoDB user groups in Dusseldorf and Frankfurt organized by codecentric AG.
The document discusses common concurrency problems in Java like shared mutable state, visibility issues, inconsistent synchronization, and unsafe publication and provides examples of how to properly implement threading concepts like locking, waiting and notifying with synchronization, volatile variables, atomic classes and safe initialization techniques to avoid concurrency bugs. It also cautions against unsafe practices like synchronizing on the wrong objects or misusing threading methods that can lead to deadlocks, race conditions and other concurrency problems.
The document provides an overview and lessons learned about developing applications with jQuery Mobile, a framework for building mobile websites and apps. It discusses jQuery Mobile concepts and architecture considerations, including using responsive design principles. It also covers challenges of testing on different devices and addressing device-specific issues like animations. The document provides code snippets and recommendations around areas like loading scripts on every page and leveraging grids.
This document discusses common concurrency problems in Java and how to address them. It covers issues that can arise from shared mutable data being accessed without proper synchronization between threads, as well as problems related to visibility and atomicity of operations. Specific problems covered include mutable statics, double-checked locking, volatile arrays, and non-atomic operations like incrementing a long. The document provides best practices for locking, wait/notify, thread coordination, and avoiding deadlocks, spin locks, and lock contention.
Qt Quick/QML brings designers and developers together to create and collaborate. QML is a collection of technologies that can build modern and fluid interfaces for applications – quickly. Join us for this webinar to explore the best of QML for mobile, embedded and desktop.
Part IV will cover:
- Dynamic Item Creation
- Keyboard Input Handling
Come hear about the highly available and massively scalable cloud storage service that is provided by Windows Azure. Learn how to create and access the different types of Windows Azure storage available, including blobs, tables, and queues.
The Ring programming language version 1.3 book - Part 7 of 88Mahmoud Samir Fayed
Ring 1.3 includes improvements to RingQt classes, the Objects library, LibCurl, and other features. Better RingQt classes allow getting event information and enabling/disabling events. The updated Objects library manages GUI objects and provides a natural API for creating windows from classes. RingLibCurl adds functions wrapping LibCurl. Other enhancements include better support for calling methods from object attributes, displaying compiler warnings, and code quality improvements.
This presentation and we will explore some of the more complex areas of QML and present tips, tricks, best practices and common areas of error and confusion. The material is based on real-world experience developing customer applications for mobile, embedded and desktop.
Part II covers:
- Anchors
- Creating New Items
- States and Transitions
Local variables are stored in memory during the execution of a function. When the function exits, the memory for local variables is deallocated. Local variables provide convenient temporary storage but have a short lifetime and cannot persist beyond the function call. Returning a pointer to a local variable from a function results in a dangling pointer as the memory is deallocated when the function exits.
O quanto você está satisfeito com o código que produz? Mais ainda: o quanto você está satisfeito como profissional? Na busca pela melhoria de nossas aplicações, caímos num grande desafio: melhorar a nós mesmos!
Numa conversa franca e descontraída, Samuel e Victor tentarão apresentar idéias sobre como você pode melhorar seu próprio trabalho e sentir orgulho do que faz.
This document describes a mobile authentication and key exchange protocol that uses nested one-time secrets. It contains modules for the user, VLR verification, HLR verification, key generation, and nested one-time secrets. The protocol uses lightweight public key cryptography and a challenge-response technique in two stages: an initial procedure and real execution stage. This allows for fast mutual authentication and agreement of a nested one-time secret while providing greater security and lower computational complexity than other wireless authentication schemes.
Example of using Kotlin lang features for writing DSL for Spark-Cassandra connector. Comparison Kotlin lang DSL features with similar features in others JVM languages (Scala, Groovy).
The document contains code for a web service class that connects to a MySQL database and provides various methods for retrieving, updating, and inserting user data. The methods include login authentication, retrieving user account information and transaction history, changing passwords, transferring funds between accounts, and getting the current account balance. The class connects to the database, executes SQL queries, and returns data to the caller.
This document discusses best practices for handling null values in Java. It recommends: failing fast with NullPointerExceptions instead of silently returning null; never returning null values from methods; marking optional parameters and return values with Java's Optional class; using Optional's map and flatMap methods to avoid deep null checks; and using Guava transforms if on Java 6/7 prior to Java 8 streams. The document provides code examples demonstrating these techniques for optional user objects returned from databases and assigned to groups.
The document describes a program for a multi-client chat client-server application using Java graphical programming. It includes the code for the ChatServer class that handles connections from multiple clients and broadcasts messages. It also includes the code for the ChatClient class that allows a client to connect to the server, send and receive messages, and view an online users list. The program allows for real-time text communication between multiple clients connected to a central server.
Behavioral Pattern of the design pattern.
Introducing 6 type patterns and also including the pros and cons. It's easy to understand what's kind of scenario it should be used.
Design pattern part 2 - structural patternJieyi Wu
This is first part: https://www.slideshare.net/JieyiWu1/design-pattern-part-1-81195876
Structural Pattern is introducing 7 type patterns and also including the pros and cons to you.
An Android operating system is an open source Linux-based OS for mobile devices. It includes application building blocks like activities, intents, broadcast receivers and services. To set up the Android development environment, developers need to install the Android SDK, Eclipse IDE, ADT plugin and create an Android virtual device. The document then provides instructions on creating an Android project in Eclipse, understanding the project structure and running an Android application.
This document summarizes a MongoDB live coding session presented by Tobias Trelle. It introduces MongoDB concepts like documents, collections, CRUD operations, queries including geospatial queries, replication, sharding, and the Java and Spring Data APIs. It also advertises MongoDB user groups in Dusseldorf and Frankfurt organized by codecentric AG.
The document discusses common concurrency problems in Java like shared mutable state, visibility issues, inconsistent synchronization, and unsafe publication and provides examples of how to properly implement threading concepts like locking, waiting and notifying with synchronization, volatile variables, atomic classes and safe initialization techniques to avoid concurrency bugs. It also cautions against unsafe practices like synchronizing on the wrong objects or misusing threading methods that can lead to deadlocks, race conditions and other concurrency problems.
The document provides an overview and lessons learned about developing applications with jQuery Mobile, a framework for building mobile websites and apps. It discusses jQuery Mobile concepts and architecture considerations, including using responsive design principles. It also covers challenges of testing on different devices and addressing device-specific issues like animations. The document provides code snippets and recommendations around areas like loading scripts on every page and leveraging grids.
The document discusses differences between the tenant representation and investment sales sides of commercial real estate brokerage. It notes that on the investment sales side, most buyers have in-house acquisition teams and do not typically pay fees to brokers. Unlike tenant representation, the investment sales field does not involve paying fees to brokers as there are few people in that business who pay fees to buying brokers. It is a different model than the tenant representation side of commercial real estate.
The document discusses ratio analysis and provides examples of balance sheets and profit and loss statements for three Indian IT companies - Satyam, Wipro, and Infosys - from March 2001. It defines key ratios used to analyze company performance and financial position, such as liquidity, gearing, asset utilization, and profitability ratios. Balance sheets show each company's assets, liabilities, and equity, while profit and loss statements provide income, expenses, and net profit figures.
This short document shows photographs of various technological items from around the home that were compiled and edited with photoshop and special effects. The author notes they could live without the technology, photoshopping, and special effects that were featured in the images.
This document lists several rugged mobile terminals and their manufacturers including the Sonim XP1 & XP3, Airo Wireless A25, and i-mate 810-f. It also mentions the manufacturers TORNADO, NOKIA, Samsung, and two Samsung models - the B2100 and A657.
Contoh bahan latihan programan mobile javaJurnal IT
This document provides examples of code for various aspects of mobile programming including:
1. Two examples of basic MIDlet code structure for starting, pausing, and destroying mobile applications.
2. Two examples of using high level user interface components like TextBox and Alert dialogs to build simple interfaces.
3. Two examples of using lower level Canvas and Graphics classes to directly draw shapes and handle user input.
4. Two examples of using the Record Management System (RMS) for basic data persistence in mobile applications.
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
The question asks to create classes to represent publications, books, and tapes. The Publication class has title and price attributes. The Book class inherits from Publication and adds a noOfPages attribute. The Tape class inherits from Publication and adds a playingTime attribute.
The document discusses testing in Android applications. It recommends moving as much logic as possible to the Java Virtual Machine (JVM) to allow for easier unit testing. This includes business logic, models, and network code using Retrofit. It also suggests using Espresso for UI testing on Android and monkeyrunner for basic OS interaction testing. The document acknowledges testing on Android can be painful due to speed and fragmentation issues, and proposes compromises like helping quality assurance engineers with tools like the Bee library.
The document discusses code refactoring and code smells. It provides an overview of code refactoring techniques such as extract class, extract method, rename method, substitute algorithm, decompose conditional, consolidate conditional expression, consolidate duplicate conditional fragments, introduce parameter object, inline temporary variable, and replace magic number with symbolic constant. It also describes common code smells like duplicated code, large class, long method, long parameter list, lazy class, switch statements, undescriptive names, temporary fields, message chains, and comments. The document emphasizes that refactoring is important to improve code quality and reduce complexity, and that developers should refactor frequently to avoid code smells.
The document discusses the history and architecture of Microsoft's .NET framework and C# programming language. It provides an overview of key .NET concepts like assemblies, application domains, and interoperability. It also summarizes major features of C# like namespaces, control flow, iterators, properties, attributes, delegates and events, LINQ, structs and constructors.
Java agents are watching your ByteCodeRoman Tsypuk
https://github.com/tsypuk/JavaAgent
Presentation about java agents in JWM.
XRebel as a starting point to demo the production agents.
Coding sesion with creating a custom java agents.
The document discusses various Kotlin language features and how they are compiled down to bytecode. It explains concepts like lowering, de-sugaring, and decompiling Kotlin programs. Specific language features summarized include free functions, nested functions, extension methods, data classes, object declarations, companion objects, and lambdas with receivers. The document shows how each feature compiles by decompiling example Kotlin code.
Le temps est révolu où Java EE ne serait qu’à développer des applications de mise à jour de données, avec JSF / EJB / JPA. Aujourd’hui Java EE s’est assoupli et s’est ouvert sur le monde, avec CDI comme clé de voûte et a repoussé nos limites grâce à des capacités d’extension puissantes et faciles d’utilisation comme JCA.
Dans un premier temps, nous reviendrons rapidement sur la place de CDI dans JavaEE 7 et sur ses mécanismes d’extension. Dans un deuxième temps, nous verrons les techniques de connecteurs JCA et comment ils peuvent aussi constituer une possibilité d’ouverture simple à mettre en œuvre. JCA fournit des techniques pour gérer des connexions sortantes ou entrantes, sur des formats ou protocoles variés.
The document contains code examples demonstrating Java programming concepts like:
1) Printing output to the console using System.out.println();
2) Declaring and initializing variables of different primitive data types;
3) Using the Scanner class to take user input;
4) Demonstrating inheritance between classes through extending superclasses; and
5) Overloading constructors.
This document provides an introduction to Java, including:
- Java is an object-oriented language developed by Sun Microsystems in 1991 that is not tied to any particular hardware or operating system.
- It discusses basic Java concepts like objects, classes, inheritance and polymorphism.
- Java applets allow programs written in Java to run within web browsers, and include init(), start(), paint(), stop() and destroy() methods.
- The document also covers client-server programming in Java using sockets, multithreaded programming, servlets, and networking protocols like TCP and UDP.
- JavaScript has come a long way from its early days of form validation and image rollovers in 1995 to modern innovations like ES2015, Promises, async/await, and Web Assembly.
- Today, JavaScript features like classes, arrow functions, and template strings in ES2015 are widely adopted, and new standards like Promises, generators, and async programming have revolutionized asynchronous JavaScript.
- Emerging web platform technologies like Web Components, Service Workers, and CSS Paint enable new kinds of custom elements, offline/progressive web apps, and painting APIs, while proposals like decorators, value types, and module loading continue pushing the language forward.
This document provides an overview of Google Web Toolkit (GWT), including its architecture, key features, and how to implement common tasks. GWT is a development toolkit that allows web applications to be written in Java and compiled into JavaScript for better cross-browser compatibility. It discusses topics like building user interfaces with widgets, event handling, styling with CSS, making remote procedure calls, and accessing native JavaScript methods. Examples and demos are provided to illustrate concepts like creating custom widgets, handling events, and making asynchronous server calls. Resources for learning more about GWT are also listed.
The document discusses various concepts related to abstraction in software development including project architecture, code refactoring, enumerations, and the static keyword in Java. It describes how to split code into logical parts using methods and classes to improve readability, reuse code, and avoid repetition. Refactoring techniques like extracting methods and classes are presented to restructure code without changing behavior. Enumerations are covered as a way to represent numeric values from a fixed set as text. The static keyword is explained for use with classes, variables, methods, and blocks to belong to the class rather than object instances.
This document discusses GUI event handling in Java. It introduces the delegation event model where event sources generate event objects that are passed to registered event listeners. It covers common event classes and listener interfaces like ActionListener, MouseListener, and WindowListener. It provides examples of handling mouse and window events using different approaches like inner classes and anonymous inner classes.
The Kotlin compiler provides many features of Kotlin that do not exist natively in the JVM by generating bytecode that emulates these features. It uses various techniques like generating additional classes and methods, passing implicit parameters, and implementing functional interfaces to achieve this. The summary decompiles some Kotlin code examples to Java bytecode to illustrate how specific Kotlin features are implemented under the hood.
The Ring programming language version 1.8 book - Part 16 of 202Mahmoud Samir Fayed
The document describes the new features and changes in Ring 1.3, including improvements to RingQt, Ring Notepad, support for the Emacs editor, additions to the standard library, improvements to loops and exit commands, new functions, and the ability to return objects by reference. It provides code examples and screenshots to illustrate the RingQt and form designer changes.
Everybody knows : Web is the platform of the future. Developing for the browser unfortunately requires us to learn and write JavaScript. Not only that but we also have to integrate the JavaScript client code with the server side, which often runs on the JVM (i.e. is written in Java). So we have to work in two different languages with completely different tools and APIs, and cannot share code between the client and the server.
The Google Web Toolkit (GWT) provides a way to write your client side web application entirely in Java and have it automatically translated to fast and compact JavaScript. It allows you to access all the browser functionality through a statically typed API. You only have to learn and use one language and you can use your code on the client as well as on the server.
The downside : Java is a bad match for the asynchronous programming model required on the browser and generally forces us to write and read a lot of boilerplate code.
In this session you'll see how programming GWT applications with Eclipse Xtend provides the best of both worlds:
Static typing with advanced IDE support meets a powerful and expressive language - right at your finger tips.
9. Singleton public class MessageBroadCaster { private static final MessageBroadCaster INSTANCE = new MessageBroadCaster(); private MessageBroadCaster() {} public static MessageBroadCaster getInstance () { return INSTANCE; } public void broadCast(final String[] messages) { final NoticeBoard board = NoticeBoard.getInstance(); int i = 0; final Message[] todayMessages = new Message[messages.length]; for(final String message : messages) { todayMessages[i++] = new Message(message); } board.show(todayMessages); } } public class NoticeBoard { private static final NoticeBoard noticeBoardInstance = new NoticeBoard(); private NoticeBoard () {} public static NoticeBoard getInstance () { return noticeBoardInstance; } public void show(final Message[] messages){ for(Message msg : messages) msg.display(); } } Global Variables are many … Class operation
13. public class MessageBroadCaster{ private NoticeBoard noticeBoard; public MessageBroadCaster(NoticeBoard noticeBoard) { this.noticeBoard = noticeBoard; } public void broadCast(final String[] messages) { int i = 0; final Message[] todayMessages = new Message[messages.length]; for(final String message : messages) { todayMessages[i++] = new Message(message); } noticeBoard.show(todayMessages); } } Abstraction class Simple implements NoticeBoard{ public void show(Message[] messages) { System.out.println("Simple Display ..."); for(Message message: messages) { System.out.println(message.getContent()); } } } Instance operation, with good abstraction
14. Modules Sequence Simple Messenger Simple Message Broadcaster Simple Notice Board sends broadcast Simple LCD Messenger LCD Message Broadcaster LCD Notice Board sends broadcast LCD Electronic Messenger Electronic Message Broadcaster Electronic Notice Board sends broadcast Electronic This is not a
15. How to create Messenger for other modules like LCD,Electronic ..etc public class Messenger { private MessageBroadCaster messageBroadCaster; public Messenger(MessageBroadCaster messageBroadCaster) { this.messageBroadCaster = messageBroadCaster; } public void send(String[] messages) { messageBroadCaster.broadCast(messages); } public static void main(String[] args) { NoticeBoard simpleNoticeBoard = new Simple (); MessageBroadCaster simpleMessageBroadCaster = new MessageBroadCaster(simpleNoticeBoard) ; Messenger simpleMessenger = new Messenger(simpleMessageBroadCaster); simpleMessenger.send (new String[] { "Welcome to Singleton" , "Town hall meet" }); } } Simple Module Simple Notice Board flow or Module has been tested.
16.
17. Program Idiom public class NoticeBoardFactory { public NoticeBoard createNoticeBoard(String type) { if("Simple".equals(type)) { return new Simple(); } else if("LCD".equals(type)){ return new LCD(); } else if("Electronic".equals(type)) { return new Electronic(); } else { return null; }}} public static void main(String[] args) { NoticeBoardFactory boardFactory = new NoticeBoardFactory(); NoticeBoard simpleNoticeBoard = boardFactory.createNoticeBoard("Simple"); MessageBroadCaster simpleMessageBroadCaster = new MessageBroadCaster(simpleNoticeBoard); Messenger simpleMessnger = new Messenger(simpleMessageBroadCaster); simpleMessnger.send(new String[] { "Welcome to Singleton" , "Town hall meet" }); } Note: We can avoid this if instead use Map, to look for specific type Creation of NoticeBoard becomes Abstract, using a program idiom
18. Module - IOC class MessengerModule{ private NoticeBoard noticeBoard; private MessageBroadCaster messageBroadCaster; private Messenger messenger; public MessengerModule(String type) { noticeBoard = new NoticeBoardFactory().createNoticeBoard(type); messageBroadCaster = new MessageBroadCaster(noticeBoard); messenger = new Messenger(messageBroadCaster); } public void send(String[] messages) { messenger.send(messages); } } MessengerModule simpleModule = new MessengerModule("Simple"); simpleModule.send(new String[] { "Welcome to Singleton" , "Town hall meet" }); MessengerModule lcdModule = new MessengerModule("LCD"); lcdModule.send(new String[] { "Welcome to Singleton" , "Town hall meet" }); MessengerModule electronicModule = new MessengerModule("Electronic"); electronicModule.send(new String[] { "Welcome to Singleton" , "Town hall meet" });
25. Test public class MessengerClient { public static void main(String[] args){ String[] messages = new String[] { "Welcome to Singleton" , "Town hall meet" }; MessengerModule.LCD.send(messages); MessengerModule.getInstance("Simple").send(messages); MessengerModule.getInstance("Electronic").send(messages); } } Output LCD Display ... Welcome to Singleton Town hall meet Simple Display ... Welcome to Singleton Town hall meet Electronic Display ... Welcome to Singleton Town hall meet