Young Jun Park (박영준)
Java back-end developer
Github : https://github.com/june0313
Y3S Study Group : https://github.com/y3s-study
Park Young Jun
2018. 09. 04
public class NaturalOrder implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
Comparator를 구현한 별도의 정렬 클래스 NaturalOrder 구현
10
15
73
99
100
List<Integer> numbers = Arrays.asList(100, 10, 15, 73, 99);
numbers.sort(new NaturalOrder());
numbers.forEach(System.out::println);
List<Integer> numbers = Arrays.asList(100, 10, 15, 73, 99);
numbers.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
numbers.forEach(System.out::println);
익명 클래스로 전략(Comparator)을 구현하여 주입
10
15
73
99
100
numbers.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
Java 8 에서는 람다식도 가능
numbers.sort((o1, o2) -> o1 - o2);
numbers.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
numbers.sort((o1, o2) -> o2 - o1);
numbers.sort(Comparator.naturalOrder());
JAVA 8에서 제공하는 기본 정렬 전략 주입
numbers.sort(Comparator.reverseOrder());
JVM이 작동하는 시스템과의 인터페이스를 제공
시스템의 메모리, 프로세서 정보 등을 확인할 수 있음
Runtime runtime = Runtime.getRuntime();
System.out.println("총 메모리" + runtime.maxMemory());
System.out.println("여유 메모리" + runtime.freeMemory());
System.out.println("코어 수" + runtime.availableProcessors());
총 메모리 : 1908932608
여유 메모리 : 126248240
코어 수 : 4
public class Runtime {
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
// 생략 ...
}
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
};
JButton button = new JButton("Click me");
button.addActionListener(actionListener);
/**
* Adds an <code>ActionListener</code> to the button.
* @param l the <code>ActionListener</code> to be added
*/
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
Observer Pattern과 Swing / AWT 비교
Observer Pattern | Swing / AWT |
---|---|
Observer | ActionListener |
Subject | JButton |
Subject.registerObserver() | JButton.addActionListener() |
Observer.update() | ActionListener.actionPerformed() |
Subject.notifyObservers() | JButton.fireActionPerformed() |
protected void fireActionPerformed(ActionEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
ActionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
// Lazily create the event:
if (e == null) {
String actionCommand = event.getActionCommand();
if(actionCommand == null) {
actionCommand = getActionCommand();
}
e = new ActionEvent(AbstractButton.this,
ActionEvent.ACTION_PERFORMED,
actionCommand,
event.getWhen(),
event.getModifiers());
}
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
InputStream, OutputStream, Reader, Writer 모두 Decorator 패턴으로 작성됨
File file = new File("data.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
}
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
}
Integer one = Integer.valueOf("1");
Long two = Long.valueOf("2");
BigDecimal three = BigDecimal.valueOf(3);
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static BigDecimal valueOf(long val) {
if (val >= 0 && val < zeroThroughTen.length)
return zeroThroughTen[(int)val];
else if (val != INFLATED)
return new BigDecimal(null, val, 0, 0);
return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
}
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = LocalDate.now();
간단한 코드를 통해 캐시 크기, 캐시 시간, 데이터 로딩 방법, 데이터 Refresh 전략을 제어 가능
public class CacheService {
private static LoadingCache<String, String> localCache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) {
return getRemoteData(key);
}
});
public String getData(String id) {
try {
return localCache.get(id);
} catch (ExecutionException e) {
return null;
}
}
private static String getRemoteData(String id) {
return "remote data";
}
}
import lombok.Builder;
@Builder
public class Person {
private String name;
private int age;
private int tall;
private int weight;
}
public static void main(String[] args) {
Person p = Person.builder()
.age(29)
.weight(100)
.tall(180)
.name("man")
.build();
}
By Young Jun Park (박영준)
디자인 패턴의 실제 활용 사례를 소개합니다.