factory
a design pattern used when a superclass has multiple subclasses that may be returned; lets a class defer instantiation to a subclass
when to use factory design pattern
if a class cannot predic t the type of object that needs to be created;
if a class wants its subclasses to specify the objects created;
if classes delegate responsibility to one of the helper subclasses
design pattern
software design incorporating best practices for a given item; well-described solutions to the most common problems during software development
singleton
ensures a JVM contains only one instance of an object; checks if an instance has been created, makes a new one if not, returns the one instance
adapter
“glues” two classes together so they are compatible; adds behavior to an object without modifying others; use when class 1 and class 2 have different methods
subject-observer
a subject/publisher notifies observers/subscribers when something changes;
maven
manage libraries, compile and package code, run tests
spring-boot
framework for building web applications
pub-sub example code
interface Observer {
void update(String message);
}
class Subscriber implements Observer {
public void update(String message) {
System.out.println(“Got update: “ + message);
}
}
class Channel {
private List<Observer> subscribers = new ArrayList<>();</Observer>
void subscribe(Observer o) {
subscribers.add(o);
}
void notifyObservers(String msg) {
for (Observer o : subscribers) {
o.update(msg);
}
} } Channel yt = new Channel(); Observer alice = new Subscriber(); yt.subscribe(alice); yt.notifyObservers("New video posted!");adapter example code
interface TargetInterface {
void request(); // Method expected by Class1
}
class Class2 {
void specificRequest() {
System.out.println(“Called specificRequest from Class2”); //method expected by class2
}
}
class AdapterClass implements TargetInterface {
private Class2 adaptee;
public AdapterClass(Class2 adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest(); // Redirect call
} }singleton example code
s1 and s2 are the same object
class Singleton {
private static Singleton instance;
private Singleton() {} // private constructor
public static Singleton getInstance() { //return existing instance
if (instance == null) { //if existing instance not found
instance = new Singleton(); //make one
}
return instance; //return existing instance, now that you're sure it exists; there will only be one
} } Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance();unittest example
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result);
} }