작성
·
51
0
abstract class IModelWithId {
final String id;
IModelWithId({required this.id});
}
인터페이스를 선언시 똑같이 했는데
@JsonSerializable()
class ProductModel implements IModelWithId {
@override
final String id;
final String name;
@JsonKey(fromJson: DataUtils.pathToUrl)
final String imgUrl;
final String detail;
final int price;
final RestaurantModel restaurant;
ProductModel({
required this.id,
required this.name,
required this.imgUrl,
required this.detail,
required this.price,
required this.restaurant,
});
factory ProductModel.fromJson(Map<String, dynamic> json) =>
_$ProductModelFromJson(json);
}
@JsonSerializable()
class ProductModel extends IModelWithId {
final String id;
final String name;
@JsonKey(fromJson: DataUtils.pathToUrl)
final String imgUrl;
final String detail;
final int price;
final RestaurantModel restaurant;
ProductModel({
required this.id,
required this.name,
required this.imgUrl,
required this.detail,
required this.price,
required this.restaurant,
}) : super(id: id);
factory ProductModel.fromJson(Map<String, dynamic> json) =>
_$ProductModelFromJson(json);
}
이 두가지 모델은 기능적으로 완전히 동일한가요?
동일하다면 구현방식은 개발자와 팀의 선호에 따라 달라지는 정도인지 궁금합니다.
그리고 인터페이스 키워드가 없다고 말씀하셨었는데 버전이 업되고 interface가 생긴것 같은데 지금과 같은 기능이면 abstract interface를 사용하는 것이 더 좋은가요?
질문을 많이 드려 죄송합니다 ㅠㅠ
답변 3
1
안녕하세요!
따지자면 동일하다는 틀린게 맞습니다.
interface는 implement하는 대상에게 구현을 맡기는 형태이고 extends는 기능을 그대로 상속합니다.
현재 예시에서는 다른점이 없지만 IModelWithId에 구현된 함수가 하나라도 생기면 완전 달라집니다.
감사합니다!
0
0
안녕하세요, 인프런 AI 인턴입니다. anwjr41님.
질문하신 내용은 두 가지 구현 방식 간의 차이에 대한 것이네요. 다음은 각각의 접근 방식에 대한 요약입니다.
Interface Implementation 방식:
class ProductModel implements IModelWithId {
// ...
}
ProductModel
이 IModelWithId
라는 인터페이스를 구현하도록 합니다.implements
키워드를 사용하여 모든 추상 메서드를 구현해야 합니다. 인터페이스 자체는 상태(예: 필드)를 가질 수 없습니다.Inheritance 방식:
class ProductModel extends IModelWithId {
// ...
}
ProductModel
이 IModelWithId
를 상속받는 구조로, 부모 클래스의 필드 및 메서드를 물려받습니다.implements
는 특정 기능 구현을 보장하는 데 주로 사용됩니다.두 방식은 클래스에 기능을 추가하는 방법이지만, 기본적으로는 다른 의도를 가지고 있습니다. extends
는 특정 클래스에서 파생된 상태나 메서드를 그대로 이어받기 원할 때 사용하고, implements
는 기능 인터페이스를 구현할 때 사용합니다.
Dart 3 이후로 interface
키워드가 추가되어 인터페이스를 보다 명확하게 정의할 수 있게 되었습니다. 인터페이스를 명시적으로 사용할 수 있기 때문에, abstract
대신 abstract interface
를 사용하는 것이 코드의 의도를 명확하게 나타내는 데 도움이 될 수 있습니다.
포럼에서 비슷한 질문을 참고해 보시면 좋겠습니다:
- “RestaurantCard에서 String? detail을 추가하는 부분에서 질문드립니다.”: Factory와 인터페이스 간의 활용에 대한 토론과 예를 보여줍니다.
- “Restaurant Card 컴포넌트 내의 factory에 대한 질문”: Factory를 구현할 때의 장단점 및 상황별 데이터 처리를 다룹니다.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.