public class FacebookPublisher implements SocialPublisher {
@Override
public String share() {
return "Facebook";
}
}
public class Millenials extends User {
public Millenials(String name) {
super(name);
this.socialPublisher = new FacebookPublisher();
}
}
public interface SocialPublisher {
String share();
}
public class TwitterPublisher implements SocialPublisher{
@Override
public String share() {
return "Twitter";
}
}
public class User {
final private String name;
protected SocialPublisher socialPublisher;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String sharePost() {
return socialPublisher.share();
}
public void setSocialPublisher(SocialPublisher socialPublisher) {
this.socialPublisher = socialPublisher;
}
}
public class YGeneration extends User {
public YGeneration(String name) {
super(name);
this.socialPublisher = new TwitterPublisher();
}
}
public class ZGeneration extends User {
public ZGeneration(String name) {
super(name);
this.socialPublisher = new SnapchatPublisher();
}
}
public class SnapchatPublisher implements SocialPublisher {
@Override
public String share() {
return "SnapChat";
}
}
//JUnit test
public class UserTestSuite {
@Test
public void testDefaultSharingStrategies() {
//Given
User user1 = new YGeneration("User1");
User user2 = new Millenials("User2");
User user3 = new ZGeneration("User3");
//When
String user1Should = user1.sharePost();
System.out.println("User1 should: " + user1Should);
String user2Should = user2.sharePost();
System.out.println("User2 should: " + user2Should);
String user3Should = user3.sharePost();
System.out.println("User3 should: " + user3Should);
//Then
Assert.assertEquals("Twitter", user1Should);
Assert.assertEquals("Facebook", user2Should);
Assert.assertEquals("SnapChat", user3Should);
}
@Test
public void testIndividualSharingStrategy() {
//Given
User user1 = new YGeneration("User1");
//When
String user1Should = user1.sharePost();
System.out.println("User1 should: " + user1Should);
user1.setSocialPublisher(new FacebookPublisher());
user1Should = user1.sharePost();
System.out.println("User1 now should: " + user1Should);
//Then
Assert.assertEquals("Facebook", user1Should);
}
}