Home » Core Java
Category Archives: Core Java
Java 8 Date Time API
Java 8 Date Time API is one of the best features in Java8.
Why Java 8 Date Time API needed ?
1. Prior to Java8 we have SimpleDateFormatter and java.util.Date and both are not Thread safe.Every application now a days requires concurrency and multithreading support.So slowly application developers started preferring 3rd party library JodaTime over java.util.Date package.This was a concern for Java Team and they come up with Java Date Time API which is thread safe.
2. Prior to Java 8 some of the date and time classes has poor API design in terms of date range.For example,default years in java.util.Date start at 1900,default months start at 1, and default days start at 0, so not very good.
3. Also Developers need to code a lot to handle TimeZone due to poor API design.
Program :::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
package com.java8.programs; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class DateTimeJava8 { public static void main(String[] args) { LocalDate localDateToday = LocalDate.now(); System.out.println("Local date : " + localDateToday); LocalDate localDateTodayWithZone = LocalDate.now(ZoneId.of("UTC")); System.out.println("Local date With UTC Zone : " + localDateTodayWithZone); LocalDateTime localDateTimeToday = LocalDateTime.now(); System.out.println("Local dateTime : " + localDateTimeToday); LocalDateTime localDateTimeTodayWithZone = LocalDateTime.now(ZoneId .of("UTC")); System.out.println("Local dateTime with UTC Zone : " + localDateTimeTodayWithZone); // equlaity check date LocalDate date1 = LocalDate.of(2018, Month.SEPTEMBER, 28); if (localDateToday.equals(date1)) { System.out.println(date1 + "and " + localDateToday + " are equal"); } else { System.out.println(date1 + "and " + localDateToday + " are not equal"); } LocalTime localTimeNow = LocalTime.now(); System.out.println("LocalTime Now : " + localTimeNow); LocalTime localTimeNowWithZone = LocalTime.now(ZoneId.of("UTC")); System.out.println("LocalTime Now with Zone: " + localTimeNowWithZone); DateTimeFormatter formatter = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("Local dateTime in yyyy-MM-dd HH:mm:ss format : " + localDateTimeToday.format(formatter)); String now = "2018-09-09 10:30"; DateTimeFormatter dateTimeFormatter = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime formatDateTime = LocalDateTime.parse(now, dateTimeFormatter); System.out.println("Local dateTime in yyyy-MM-dd HH:mm format : " + formatDateTime); Instant instatNow = Instant.now(); System.out.println("InstatNow : " + instatNow + " Instant later : " + instatNow.plusSeconds(60) + " Instant Before : " + instatNow.minusSeconds(60)); ZonedDateTime zonedDateTime = localDateTimeToday.atZone(ZoneId.of("Asia/Kolkata")); System.out.println("ZonedDateTime Asia/Kolkata : " + formatter.format(zonedDateTime)); Clock clock = Clock.systemUTC(); System.out.println("Clock : " + clock); } } |
Output ::
1 2 3 4 5 6 7 8 9 10 11 12 |
Local date : 2018-09-28 Local date With UTC Zone : 2018-09-28 Local dateTime : 2018-09-28T10:01:45.813 Local dateTime with UTC Zone : 2018-09-28T04:31:45.814 2018-09-28and 2018-09-28 are equal LocalTime Now : 10:01:45.814 LocalTime Now with Zone: 04:31:45.814 Local dateTime in yyyy-MM-dd HH:mm:ss format : 2018-09-28 10:01:45 Local dateTime in yyyy-MM-dd HH:mm format : 2018-09-09T10:30 InstatNow : 2018-09-28T04:31:45.846Z Instant later : 2018-09-28T04:32:45.846Z Instant Before : 2018-09-28T04:30:45.846Z ZonedDateTime Asia/Kolkata : 2018-09-28 10:01:45 Clock : SystemClock[Z] |
Sort Map by Key and by Value using Java8
Question : Write a program using java 8
1. sort a map by key in natural order
2. sort a map by key in reverse order
3. sort a map by value in natural order
4. sort a map by value in reverse order
Solution ::
The below program takes a hashmap as input and sorts the map by key and by value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
package com.java8.programs; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; public class MapSortJava8 { public static void main(String[] args){ Map<Integer,String> originalMap = new HashMap<Integer,String>(); originalMap.put(1, "Ajay"); originalMap.put(5, "Bijay"); originalMap.put(3, "Asha"); originalMap.put(4, "Jyoti"); originalMap.put(2, "Chinmaya"); System.out.println("Original Map"); originalMap.forEach((key,value) -> System.out.println(key+" :"+value)); // sorts the hashmap by key in natural order // using Comparator.naturalOrder method Map<Integer, String> sortedKeyMap = originalMap .entrySet() .stream() .sorted(Map.Entry.comparingByKey(Comparator.naturalOrder())) .collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println("\nSortedKey Map in natural Order"); sortedKeyMap.forEach((key,value) -> System.out.println(key+" :"+value)); // sorts the hashmap by key in reverse order // using Comparator.reverseOrder method sortedKeyMap = originalMap .entrySet() .stream() .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) .collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println("\nSortedKey Map in reverse Order"); sortedKeyMap.forEach((key,value) -> System.out.println(key+" :"+value)); // sorts the hashmap by value in natural order // using Comparator.naturalOrder method Map<Integer, String> sortedValueMap = originalMap .entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.naturalOrder())) .collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println("\nSortedValue Map in natural Order"); sortedValueMap.forEach((key,value) -> System.out.println(key+" :"+value)); // sorts the hashmap by value in reverse order // using Comparator.reverseOrder method sortedValueMap = originalMap .entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println("\nSortedValue Map in Reverse Order"); sortedValueMap.forEach((key,value) -> System.out.println(key+" :"+value)); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
Original Map 1 :Ajay 2 :Chinmaya 3 :Asha 4 :Jyoti 5 :Bijay SortedKey Map in natural Order 1 :Ajay 2 :Chinmaya 3 :Asha 4 :Jyoti 5 :Bijay SortedKey Map in reverse Order 5 :Bijay 4 :Jyoti 3 :Asha 2 :Chinmaya 1 :Ajay SortedValue Map in natural Order 1 :Ajay 3 :Asha 5 :Bijay 2 :Chinmaya 4 :Jyoti SortedValue Map in Reverse Order 4 :Jyoti 2 :Chinmaya 5 :Bijay 3 :Asha 1 :Ajay |
Java Enum
Java Enum Overview ::
1. In java an enum type is a special data type which enables a variable to hold a set of predefined constants.It means basically enum is a datatype which can hold a set of constants.
2. Directions(EAST,WEST,NORTH,SOUTH) is an example of enum or DAY(SUN,MON,TUE,WED,THU,FRI,SAT) is an example of enum.
3. enum can be traversed using values() method.
4. enum can have constructor,fields and also user defined methods.
5. enum internally extends enum class ,so it can not extend any other class .enum can implement multiple interfaces.
1 2 3 |
public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable |
6. enum can be used in switch statements,enum is final so we can use for Singleton,enum ensures type safety as well.These are some of the reasons why we use enum.
7. You can use valueOf(String arg) to get a particular enum and you can use valueOf(Class<T> arg, String arg1) to get a particular enum of a class Type.
8. enum was introduced in Java 5 version jdk 1.5
You can directly create enum java file by following the below image.
Let us create an enum called Apartment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.ai1tutorial.email; public enum Apartment { BHK_1("1BHK",500000), BHK_2("2BHK",700000), BHK_3("3BHK",900000), VILLA_4BHK("4BHKVILLA",12000000); private String houseType; private int price; private Apartment(String houseType, int price) { this.houseType = houseType; this.price = price; } public String getHouseType() { return houseType; } public int getPrice() { return price; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.ai1tutorial.email; public class EnumDemo { public static void main(String[] args) { System.out.println("ApartmentType AparmentPrice($)"); for (Apartment apartment : Apartment.values()) { System.out.println(apartment.getHouseType() + "------------------->>>$" + apartment.getPrice()); } System.out.println("4BHK Villa Price " + Apartment.VILLA_4BHK.getPrice()); } } |
Output ::
1 2 3 4 5 6 |
ApartmentType AparmentPrice($) 1BHK------------------->>>$500000 2BHK------------------->>>$700000 3BHK------------------->>>$900000 4BHKVILLA------------------->>>$12000000 4BHK Villa Price 12000000 |
Java Regular Expressions
Java Regular Expressions ::
1. java.util.regex API is used for pattern matching using regular expressions
2. java.util.regex.Pattern and java.util.regex.Matcher are the two main classed in java.util.regex API.
3. class java.util.regex.Pattern extends Object class and implements Serializable class.
4. A regular expression, specified as a string, must first be compiled into an instance of Pattern class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.
Validate Email address with regular expression
Write a Program to validate Email address with regular expression ?
ValidEmailMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.ai1tutorial.regex.programs; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidEmailMain { private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; public static void main(String[] argv) { checkIfValidEmail("abc@ai1tutorial.com"); checkIfValidEmail("abcai1tutorial.com"); // @ is missing checkIfValidEmail("abc@ai1tutorial");// .com is missing checkIfValidEmail("abc@ai1tutorialcom");// . is missing before com checkIfValidEmail("abc@@ai1tutorial.com");// multiple @@ checkIfValidEmail("abc@@ai1.tutorial.com");// multiple . checkIfValidEmail("111@@111.111");// all numbers checkIfValidEmail(null);// invalid will throw NullPointerException if not // handled checkIfValidEmail("");// empty string should be invalid } public static void checkIfValidEmail(String ipAddress) { if (null != ipAddress) { Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(ipAddress); if (matcher.find()) { System.out.println(ipAddress + " is a valid Email Adresss"); } else { System.out.println(ipAddress + " is not a valid Email Adresss"); } } } } |
Output ::
1 2 3 4 5 6 7 8 |
abc@ai1tutorial.com is a valid Email Adresss abcai1tutorial.com is not a valid Email Adresss abc@ai1tutorial is not a valid Email Adresss abc@ai1tutorialcom is not a valid Email Adresss abc@@ai1tutorial.com is not a valid Email Adresss abc@@ai1.tutorial.com is not a valid Email Adresss 111@@111.111 is not a valid Email Adresss is not a valid Email Adresss |
Validate IP address with regular expression
Write a Program to validate IP address with regular expression ?
ValidIPMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.ai1tutorial.sample.programs; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidIPMain { private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; public static void main(String[] argv) { checkIfValidIP("0.0.0.0"); // all zeroes checkIfValidIP("23.24.25");// not 4 checkIfValidIP("10.10.10.222");// valid ip checkIfValidIP("23.24.25.b");// must be numbers checkIfValidIP("a.b.c.d");// must be numbers checkIfValidIP("13.12.11.257");// each should be [0-255] range checkIfValidIP("13.12.011.255");// can take zero checkIfValidIP(null);// invalid will throw NullPointerException if not // handled checkIfValidIP("");// empty string should be invalid } public static void checkIfValidIP(String ipAddress) { if (null != ipAddress) { Pattern pattern = Pattern.compile(IPADDRESS_PATTERN); Matcher matcher = pattern.matcher(ipAddress); if (matcher.find()) { System.out.println(ipAddress + " is a valid IP Adresss"); } else { System.out.println(ipAddress + " is not a valid IP Adresss"); } } } } |
Output ::
1 2 3 4 5 6 7 8 |
0.0.0.0 is a valid IP Adresss 23.24.25 is not a valid IP Adresss 10.10.10.222 is a valid IP Adresss 23.24.25.b is not a valid IP Adresss a.b.c.d is not a valid IP Adresss 13.12.11.257 is not a valid IP Adresss 13.12.011.255 is a valid IP Adresss is not a valid IP Adresss |
Java8-ForEach
In this post we are going to code forEach() and forEachOrdered() examples. forEach() method is used to iterate over a collection like List,Set,Map etc or a stream.forEachOrdered() method process the elements in the order the elements are added to collection.
Syntax ::
1 2 3 |
// * Performs an action for each element of this stream. void forEach(Consumer<? super T> action); |
1 2 3 |
// Performs an action for each element of this stream, in the encounter // * order of the stream if the stream has a defined encounter order. void forEachOrdered(Consumer<? super T> action); |
Program ::
In the below Program I have used three methods to use forEach() over List,Set and Map.I have used the same method to show forEachOrdered() on List and Set using stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
package com.ai1tutorial.java8.features; import java.util.*; public class ForEachLoopExmples { public static void main(String[] args){ forEachListExample(); forEachSetExample(); forEachMapExample(); } private static void forEachListExample(){ System.out.println("Inside forEachListExample"); List<String> nameList = new ArrayList<String>(); nameList.add("Ajay"); nameList.add("Jyoti"); nameList.add("Bijay"); nameList.forEach(System.out::println); nameList.forEach(name->System.out.println(name)); System.out.println("Using forEachOrdered in namList"); nameList.stream().forEachOrdered(System.out::println); //print names containing ay nameList.forEach(name->{ if(name.contains("ay")) { System.out.println(name); } }); //Stream and filter names containing Jyo nameList.stream() .filter(name->name.contains("Jyo")) .forEach(System.out::println); } private static void forEachSetExample(){ System.out.println("Inside forEachSetExample"); Set<String> nameSet = new LinkedHashSet<>(); nameSet.add("Ajay"); nameSet.add("Jyoti"); nameSet.add("Bijay"); //print all names nameSet.forEach(System.out::println); //print all names nameSet.forEach(name->System.out.println(name)); System.out.println("Using forEachOrdered in nameSet"); nameSet.stream().forEachOrdered(System.out::println); //print names containing ay nameSet.forEach(name->{ if(name.contains("ay")) { System.out.println(name); } }); //Stream and filter names containing Jyo nameSet.stream() .filter(name->name.contains("Jyo")) .forEach(System.out::println); } private static void forEachMapExample(){ Map<Integer,String> nameMap = new HashMap<Integer,String>() ; nameMap.put(1,"Ajay"); nameMap.put(2,"Jyoti"); nameMap.put(3,"Bijay"); nameMap.forEach((k,v)->System.out.println("Rank : " + k + " Name : " + v)); nameMap.forEach((k,v)->{ System.out.println("Rank : " + k + " Name : " + v); if(v.contains("Jyo")){ System.out.println("Welcome "+v); } }); } } |
Output ::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
Inside forEachListExample Ajay Jyoti Bijay Ajay Jyoti Bijay Using forEachOrdered in namList Ajay Jyoti Bijay Ajay Bijay Jyoti Inside forEachSetExample Ajay Jyoti Bijay Ajay Jyoti Bijay Using forEachOrdered in nameSet Ajay Jyoti Bijay Ajay Bijay Jyoti Rank : 1 Name : Ajay Rank : 2 Name : Jyoti Rank : 3 Name : Bijay Rank : 1 Name : Ajay Rank : 2 Name : Jyoti Welcome Jyoti Rank : 3 Name : Bijay |
Abstract Factory Design Pattern
Abstract Factory Design Pattern ::Abstract Factory design pattern is also called as factory of factories. This type of design pattern comes under creational design pattern as this pattern provides way to select a factory and then create an instance of related classes of that factory.
Real Time Example :: I am going to have two factories where one factory will have VideoPlayer and its implementation classes and another factory will have AudioPlayer and and its implementation classes.Based on user input a factory will be selected and then an instance will be created of related classed of that factory.
UML Diagram ::
Step 1 :
Create an Interface VideoPlayer .java and declare method playVideo()
1 2 3 4 5 6 7 |
package com.ai1tutorial.design.patterns.abstractfactory; public interface VideoPlayer { public void playVideo(); } |
Step 2 :
Create a class VlcMediaPlayer.java which implements interface VideoPlayer.java and has its own implementation for method playVideo()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public class VlcMediaPlayer implements VideoPlayer { public void playVideo() { System.out.println("Playing your favourite video using VLC MediaPlayer"); } } |
Step 3 :
Create a class WindowsMediaPlayer.java which implements interface VideoPlayer.java and has its own implementation for method playVideo()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public class WindowsMediaPlayer implements VideoPlayer { public void playVideo() { System.out.println("Playing your favourite video using Windows MediaPlayer"); } } |
Step 4 :
Create a class AdobeFlashPlayer.java which implements interface VideoPlayer.java and has its own implementation for method playVideo()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public class AdobeFlashPlayer implements VideoPlayer { public void playVideo() { System.out.println("Playing your favourite video using Adobe Flash Player"); } } |
Step 5 :
Create an Interface AudioPlayer.java and declare method playSong()
1 2 3 4 5 6 7 |
package com.ai1tutorial.design.patterns.abstractfactory; public interface AudioPlayer { public void playSong(); } |
Step 6 :
Create a class WinAmpPlayer .java which implements interface AudioPlayer.java and has its own implementation for method playSong()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public class WinAmpPlayer implements AudioPlayer { public void playSong() { System.out.println("Playing your favourite song using WinAmp Player"); } } |
Step 7 :
Create a class MP3Player.java which implements interface AudioPlayer.java and has its own implementation for method playSong()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public class MP3Player implements AudioPlayer { public void playSong() { System.out.println("Playing your favourite song using MP3 Player"); } } |
Step 8 :
Create a class JetAudioHDPlayer.java which implements interface AudioPlayer.java and has its own implementation for method playSong()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public class JetAudioHDPlayer implements AudioPlayer { public void playSong() { System.out.println("Playing your favourite song using JetAudioHD Player"); } } |
Step 9:
Create an abstract class AbstractFactory.java which has two abstract methods getVideoPlayer() and getAudioPlayer() which returns VideoPlayer and AudioPlayer type instances respectively.
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns.abstractfactory; public abstract class AbstractFactory { abstract VideoPlayer getVideoPlayer(String videoPlayerType); abstract AudioPlayer getAudioPlayer(String audioPlayerType); } |
Step 10 :
Create a class VideoPlayerFactory .java which extends AbstractFactory class and returns corresponding VideoPlayer type instance based on user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.ai1tutorial.design.patterns.abstractfactory; public class VideoPlayerFactory extends AbstractFactory{ // based on user input corresponding //class instance will be created public VideoPlayer getVideoPlayer(String videoPlayerType) { if ("VLC".equalsIgnoreCase(videoPlayerType)) { return new VlcMediaPlayer(); } else if ("WINDOWS".equalsIgnoreCase(videoPlayerType)) { return new WindowsMediaPlayer(); } else if ("ADOBE".equalsIgnoreCase(videoPlayerType)) { return new AdobeFlashPlayer(); } return null; } @Override AudioPlayer getAudioPlayer(String audioPlayerType) { return null; } } |
Step 12 :
create a class AudioPlayerFactory.java which extends AbstractFactory class and returns corresponding AudioPlayer type instance based on user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.ai1tutorial.design.patterns.abstractfactory; public class AudioPlayerFactory extends AbstractFactory { // based on user input corresponding //class instance will be created public AudioPlayer getAudioPlayer(String audioPlayerType) { if ("WINAMP".equalsIgnoreCase(audioPlayerType)) { return new WinAmpPlayer(); } else if("MP3".equalsIgnoreCase(audioPlayerType)){ return new MP3Player(); } else if("JETAUDIOHD".equalsIgnoreCase(audioPlayerType)){ return new JetAudioHDPlayer(); } return null; } @Override public VideoPlayer getVideoPlayer(String videoPlayerType) { return null; } } |
Step 13 :
Create class SelectFactory.java which has public method getFactory() that returns corresponding VideoPlayerFactory or AudioPlayerFactory type instance based on user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.ai1tutorial.design.patterns.abstractfactory; public class SelectFactory { public static AbstractFactory getFactory(String factoryType){ if("VIDEO".equalsIgnoreCase(factoryType)){ return new VideoPlayerFactory(); }else if("AUDIO".equalsIgnoreCase(factoryType)){ return new AudioPlayerFactory(); } return null; } } |
Step 14 :
Create class AbstractFactoryDesignPatternDemo.java and select factory and then corresponding class object of that factory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.ai1tutorial.design.patterns.abstractfactory; public class AbstractFactoryDesignPatternDemo { public static void main(String[] args){ AbstractFactory videoFactory = SelectFactory.getFactory("VIDEO"); VideoPlayer vlcPlayer = videoFactory.getVideoPlayer("VLC"); vlcPlayer.playVideo(); VideoPlayer windowsPlayer = videoFactory.getVideoPlayer("WINDOWS"); windowsPlayer.playVideo(); VideoPlayer adobePlayer = videoFactory.getVideoPlayer("ADOBE"); adobePlayer.playVideo(); System.out.println(); AbstractFactory audioFactory = SelectFactory.getFactory("AUDIO"); AudioPlayer winAmpPlayer = audioFactory.getAudioPlayer("WINAMP"); winAmpPlayer.playSong(); AudioPlayer mp3Player = audioFactory.getAudioPlayer("MP3"); mp3Player.playSong(); AudioPlayer jetAudioHdPlayer = audioFactory.getAudioPlayer("JETAUDIOHD"); jetAudioHdPlayer.playSong(); } } |
Output ::
Playing your favourite video using VLC MediaPlayer
Playing your favourite video using Windows MediaPlayer
Playing your favourite video using Adobe Flash Player
Playing your favourite song using WinAmp Player
Playing your favourite song using MP3 Player
Playing your favourite song using JetAudioHD Player
Observer Design Pattern
Observer Design Pattern :: Observer Design Pattern comes under behvioral design pattern.In this design pattern an observer is notified if any changes occur to an object which the observer is subscribed to.
Real Time Example :: Suppose there are serveral readers.One category of readers like to read Java Topics and other set of readers like to read Spring Topics .So these readers(Observers) first subscribes to corresponding SubjectTopic(Subjects).Once any changes to Subject, new articles added to topic and any subscriber is added/removed then if reader/subscriber opts for notification he/she can get the notification about the same.
UML Diagram ::
Step 1 :
Create an Interface Subject.java and declare methods subscribeObsever(Observer observer),unSubscribeObsever(Observer observer) and notifyAllObsevers() .
subscribeObsever() method adds an Observer/Subscriber.
unSubscribeObsever method removes an Observer/Subscriber.
notifyAllObsevers() method notify all Observers/Subscribers currently subscribed for the Subject.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.ai1tutorial.design.patterns; package com.ai1tutorial.design.patterns.observer; public interface Subject { public void subscribeObsever(Observer observer); public void unSubscribeObsever(Observer observer); public void notifyAllObsevers(); } |
Step 2 :
Create an Interface Observer.java and declare methods updateObserver() .
updateObserver() method updates an Observer/Subscriber if any changes happen to Subject.
I have also optionally added getName() method to get details about Observer/Subscriber.
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns; package com.ai1tutorial.design.patterns.observer; public interface Observer { public void updateObserver(); public String getName(); // Optionally added to print observer details } |
Step 3 :
Create a class TopicEnrollment.java which implements interface Subject.java and has its own implementation for methods subscribeObsever(Observer observer),unSubscribeObsever(Observer observer) and notifyAllObsevers() .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.ai1tutorial.design.patterns.observer; import java.util.ArrayList; public class TopicEnrollment implements Subject { private String topic; private ArrayList<Observer> list; public TopicEnrollment(String topic) { super(); this.topic = topic; this.list = new ArrayList<Observer>(); } public void subscribeObsever(Observer observer) { this.list.add(observer); System.out.println("Subscriber "+observer.getName() +" subscribed to topic "+this.topic); } public void unSubscribeObsever(Observer observer) { this.list.remove(observer); System.out.println("Subscriber "+observer.getName() +" unsubscribed from topic "+this.topic); } public void notifyAllObsevers() { for (Observer obsever : this.list) { obsever.updateObserver(); } } } |
Step 4 :
Create a class Subsrciber.java which implements interface Observer.java and has its own implementation for methods updateObserver()nd getName()
I also have an instance of Subject here ,so that a Subscriber can subscribe to corresponding Subject.I am doing the same in the constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.ai1tutorial.design.patterns.observer; public class Subsrciber implements Observer { private Subject subject; private String name; public Subsrciber(String name,Subject subject) { super(); this.name = name; this.subject = subject; this.subject.subscribeObsever(this); } public String getName() { return this.name; } public void updateObserver() { System.out.println("Subscriber "+this.name+ " is notified"); } } |
Step 5 :
Create main class ObserverDesignPatternDemo.java.I have created two topics “java-8” and “Spring-5” to demo Observer design pattern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.ai1tutorial.design.patterns.observer; public class ObserverDesignPatternDemo { public static void main(String[] args){ Subject javaTopic = new TopicEnrollment("java-8"); Observer javaReader1 = new Subsrciber("Kate",javaTopic); Observer javaReader2 = new Subsrciber("Penelope",javaTopic); Observer javaReader3 = new Subsrciber("Anne",javaTopic); javaTopic.notifyAllObsevers(); javaTopic.unSubscribeObsever(javaReader1); javaTopic.notifyAllObsevers(); System.out.println("\n\n"); Subject springTopic = new TopicEnrollment("Spring-5"); Observer springReader1 = new Subsrciber("John",springTopic); Observer springReader2 = new Subsrciber("Arjun",springTopic); Observer springReader3 = new Subsrciber("Hrithik",springTopic); springTopic.notifyAllObsevers(); springTopic.unSubscribeObsever(springReader3); springTopic.notifyAllObsevers(); } } |
<
Output ::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Subscriber Kate subscribed to topic java-8 Subscriber Penelope subscribed to topic java-8 Subscriber Anne subscribed to topic java-8 Subscriber Kate is notified Subscriber Penelope is notified Subscriber Anne is notified Subscriber Kate unsubscribed from topic java-8 Subscriber Penelope is notified Subscriber Anne is notified Subscriber John subscribed to topic Spring-5 Subscriber Arjun subscribed to topic Spring-5 Subscriber Hrithik subscribed to topic Spring-5 Subscriber John is notified Subscriber Arjun is notified Subscriber Hrithik is notified Subscriber Hrithik unsubscribed from topic Spring-5 Subscriber John is notified Subscriber Arjun is notified |
Factory Design Pattern
Factory Design Pattern :: Factory Design Pattern comes under creation design pattern.As the name suggests,basically using these design pattern you can create an instance of class from a factory of related classes.
Real Time Example :: I am going to have a factory of MediaPlayer classes and each class has the functionality to play song.Based on user input ,user will select a particular type media player and will play song using that media player only.
UML Diagram ::
Step 1 :
Create an Interface MediaPlayer.java and declare method playSong()
1 2 3 4 5 6 7 |
package com.ai1tutorial.design.patterns; public interface MediaPlayer { public void playSong(); } |
Step 2 :
Create a class VlcMediaPlayer.java which implements interface MediaPlayer.java and has its own implementation for method playSong()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns; public class VlcMediaPlayer implements MediaPlayer{ public void playSong() { System.out.println("Playing your favourite video using VLC MediaPlayer"); } } |
Step 3 :
Create a class WindowsMediaPlayer.java which implements interface MediaPlayer.java and has its own implementation for method playSong()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns; public class WindowsMediaPlayer implements MediaPlayer{ public void playSong() { System.out.println("Playing your favourite video using Windows MediaPlayer"); } } |
Step 4 :
Create a class AdobeFlashPlayer.java which implements interface MediaPlayer.java and has its own implementation for method playSong()
1 2 3 4 5 6 7 8 9 |
package com.ai1tutorial.design.patterns; public class AdobeFlashPlayer implements MediaPlayer{ public void playSong() { System.out.println("Playing your favourite video using Adobe Flash Player"); } } |
Step 5 :
Create a class MediaPlayerFactory.java and expose a public method which accepts an input and create instance of the corresponding class based on input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.ai1tutorial.design.patterns; public class MediaPlayerFactory { // based on user input corresponding //class instance will be created public MediaPlayer getMediaPlayer(String mediaPlayerType) { if ("VLC".equalsIgnoreCase(mediaPlayerType)) { return new VlcMediaPlayer(); } else if ("WINDOWS".equalsIgnoreCase(mediaPlayerType)) { return new WindowsMediaPlayer(); } else if ("ADOBE".equalsIgnoreCase(mediaPlayerType)) { return new AdobeFlashPlayer(); } return null; } } |
Step 6 :
Create Main class FactoryDesignPatternDemo.java and create MediaPlayerFactory instance. Pass input tho the public method of MediaPlayerFactory class and get corresponding instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.ai1tutorial.design.patterns; public class FactoryDesignPatternDemo { public static void main(String[] args){ MediaPlayerFactory mediaFctory = new MediaPlayerFactory(); //Pass "VLC" as argument value to get object of //VlcMediaPlayer from MediaPlayerFactory class MediaPlayer vlc = mediaFctory.getMediaPlayer("VLC"); vlc.playSong(); MediaPlayer windows = mediaFctory.getMediaPlayer("WINDOWS"); windows.playSong(); MediaPlayer adobe = mediaFctory.getMediaPlayer("ADOBE"); adobe.playSong(); } } |
Output ::
1 2 3 |
Playing your favourite video using VLC MediaPlayer Playing your favourite video using Windows MediaPlayer Playing your favourite video using Adobe Flash Player |