Tag Archive for 'Java'

Why abstract Method

상속가능한 메소드 구현(즉, 실제본체가 있는 메소드)은 상위 클래스에 집어넣기에 딱 좋다.
하지만 추상 클래스에서는 하위 클래스에서 유용하게 써먹을 수 있는 일반적인 코드를 전혀 만들 수 없기 때문에 메소드를 구현한다는 것이 아예 말이 안 되는 경우가 종종 있다. 추상메소드를 만드는 이유는 실제 메소드 코드를 전혀 집어넣지는 않더라도 일련의 하위클래스를 위한 규약(protocol)의 일부를 정의하기 위한 것이다.

그렇다면 장점은?…….

OOP의 핵심이라 할 수 있는 다형성(polymorphism)이다.
상위클래스 유형을 메소드의 인자나 리턴유형 또는 배열유형으로 쓸 수 있게 만드는 능력이 필요하다. 그래야만 새로운 유형을 처리하기 위한 새로운 메소드를 추가하거나 기존의 메소드를 고칠 필요없이 프로그램에 새로운 하위클래스 유형을 추가할 수 있기 때문이다.

플래시에서는 추상클래스를 지원하지는 않는다.
하지만 추상클래스 보다 더 추상적인 개념인 인터페이스(interface)가 존재한다. 물론 자바에서 사용되는 인터페이스와 똑같다.
앞으로 사용될 AS3.0 에서도 추상클래스는 지원하지 않지만 인터페이스 만으로도 비슷한 역할을 구현할 수 있을 것이다.

Classes in As and Java or C++

[퍼온글] 출처 : <Flex 2 language Reference 36 page>

Programmers familiar with object-oriented programming (OOP) in Java or C++ may think of objects as modules that contain two kinds of members: data stored in member variables or properties, and behavior accessible through methods. The ECMAScript edition 4 draft, the standard upon which ActionScript 3.0 is based, defines objects in a similar but slightly different way. In the ECMAScript draft, objects are simply collections of properties. These properties are containers that can hold not only data, but also functions or other objects. If a function is attached to an object in this way, it is called a method.
While the ECMAScript draft definition may seem a little odd to programmers with a Java or C++ background, in practice, defining object types with ActionScript 3.0 classes is very similar to the way classes are defined in Java or C++. The distinction between the two definitions of object is important when discussing the ActionScript object model and other advanced topics, but in most other situations the term properties means class member variables as opposed to methods. The Flex 2 Language Reference, for example, uses the term properties to mean variables or getter-setter properties. It uses the term methods to mean functions that arepart of a class.

One subtle difference between classes in ActionScript and classes in Java or C++ is that in ActionScript, classes are not just abstract entities. ActionScript classes are represented by class objects that store the class’s properties and methods. This allows for techniques that may seem alien to Java and C++ programmers, such as including statements or executable code at the top level of a class or package.

Another difference between ActionScript classes and Java or C++ classes is that every ActionScript class has something called a prototype object. In previous versions of ActionScript, prototype objects, linked together into prototype chains, served collectively as the foundation of the entire class inheritance hierarchy. In ActionScript 3.0, however, prototype objects play only a small role in the inheritance system. The prototype object can still be useful, however, as an alternative to static properties and methods if you want to share a property and its value among all the instances of a class.

In the past, advanced ActionScript programmers could directly manipulate the prototype chain with special built-in language elements. Now that the language provides a more mature implementation of a class-based programming interface, many of these special language elements, such as __proto__ and __resolve, are no longer part of the language.

Moreover, optimizations of the internal inheritance mechanism that provide significant Flash Player performance improvements preclude direct access to the inheritance mechanism.
actionscript 와 java or c++ 의 class 간의 개념이 약간 다르다.
어찌보면 다아나믹한 움직임을 구현하기 위해선 필요한 차이점인지 모른다.
그래도 ECMAScript 기반의 언어라 그런지 java 와는 외향이 거의 흡사해진다는 느낌이다.

prototype 은 뭔가 꺼림직해서 이전부터 건드리지 않은 부분이지만 아니나 다를까 성능에 문제가 있을 수 있다고 하니 protoype object 는 터치하지 말아야 겠다…

Adapter pattern(1)

상속에 의한 Adapter 패턴 -  가장 기본이 되는 클래스를 중심으로 클래스를 확장하는 방법으로 인터페이스로 구현하는 방식, 어쩌면 클래스 확장에 있어 가장 기본이 되는 디자인 패턴인듯 싶다.

플래시에서도 가장 쉽게 적용되는 방식이다.

*Adaptee – Banner Class

접합하는 측이 아니라 접합되는 측. 이미 준비되어있는 메소드를 가지고 있는 역할.

public class Banner{
  private String string;
 
  public Banner(String string){
  this.string=string;
  }
 
  public void showWithParen(){
    System.out.printIn("("+string+")");
  }
 
  public void showWithAster(){
    System.out.printIn("*"+string+"*");
  }
 
}

*Target – Print Interface

필요로 하는 메소드를 제공하는 역할.

 public interface Print{
    public abstract void printWeak();
 
    public abstract void printStrong();
 
}

*Adapter – PrintBanner Class

Adaptee 역할의 메소드를 사용하여 Target 역할을 충족시키는 역할.

public class PrintBanner extends Banner implements Print{
 
public PrintBanner(String string){
    super(string);
}
 
public void printWeak(){
  showWithParen();
}
 
public void printStrong(){
  showWithAster();
}
 
}

*Client – Main Class

Target 역할의 메소드를 사용해서 일을 하는 역할

public class Main{
 
public static void main(String[] args){
 
Print p= new PrintBanner("Hellow");
 
p.printWeak();
 
p.printStrong();
 
}
 
}

Print interface 를 사용하여 구현하고 있다는 점을 강조하기 위해 인스턴스 변수를 Print 형 변수에 대입하여 사용함…

The Design Patterns in Java

The Design Patterns in Java : Table of Contents

Some Background on Design Patterns
Object-Oriented Programming Concepts
Defining Design Patterns
1. Creational Patterns
The Factory Pattern
The Abstract Factory Pattern
The Singleton Factory Pattern
The Builder Pattern
The Prototype Pattern
Summary of Creational Patterns
2. Structural Patterns
The Adapter Pattern
The Bridge Pattern
The Composite Pattern
The Decorator Pattern
The Facade Pattern
The Flyweight Pattern
The Proxy Pattern
The Summary of Patterns
3. Behavioral Patterns
Chain of Responsibility
The Command Pattern
The Interpreter Pattern

The Iterator Pattern

The Mediator Pattern
The Memento Pattern
The Observer Pattern
The State Pattern
The Strategy Pattern
The Template Pattern
The Visitor Pattern
Appendix
Standard Coding Rules
UML
References

java에서 리소스 사용의 균형

C++과 달리 자바에서는 게으른 방식의 자동 객체 삭제를 사용한다. 참조가 없는 객체들은 가비지 콜랙션(garbage collection)의 후보가 되며, 만약 가비지 콜랙션이 그 객체들을 지우려고 하기만 한다면, 객체의 finalize 메서드가 호출될 것이다.

더이상 대부분 메모리 누수 책임을 지지 않게 되어 개발자에게는 아주 편해진 일이지만, C++방식대로 자원을 청소하도록 구현하기는 어려워졌다.

다행스럽게도 사려깊은 자바 언어의 설계자들은 이것을 보상하기 위한 기능 하나를 추가해두었다.

finally 절이 그것이다. try 블록에 finally절이 들어있다면, 그절안의 코드들은 try 블록 안의 코드가 한문장이라도 실행되면 반드시 실행되도록 되어있다. 예외가 던져지더라도 상관없다.

finally 절 안의 코드는 반드시 실행된다. 이말은 다음과 같은 코드로 리소스 사용의 균형을 잡을 수 있다는 뜻이다.

public void dosomething() throws IOException{
 
       File tmpFile = new File(tmpFileName);
       FileWriter tmp = new FileWriter(tmpFile);
 
       try{
               //실행코드
       }
       finally{
               tmpFile.delete();
       }
}

이 루틴에서 사용한 임시파일은 루틴에서 어떻게 나가든 지워야 한다.
finally 블록이 이렇게 간결하게 해결해 준다.