Development Tip

캡슐화 및 추상화를 이해하는 간단한 방법

yourdevel 2020. 11. 12. 20:27
반응형

캡슐화 및 추상화를 이해하는 간단한 방법


추상화 및 캡슐화를 심층적으로 이해하는 데 특히 관심이있는 OOP 개념 학습.

이미 아래를 확인했습니다.

추상화 VS 정보 숨기기 VS 캡슐화

추상화와 캡슐화의 차이점은 무엇입니까?

실제 간단한 예제 클래스 / 코드 스 니펫 없이는 이러한 개념을 이해하기가 매우 어려웠습니다.

내 동료 중 한 명이 추상화는 추상 클래스를 만들고 범위로 멤버 변수를 보호하는 일반 클래스를 캡슐화라고합니다.

아래 내용을 반복하지 않고 다른 사람들이 정확히 무엇인지 이해하고 이해할 수있는 간단한 방법이 있습니까?

추상화와 캡슐화는 상호 보완적인 개념입니다. 추상화는 객체의 관찰 가능한 동작에 중점을 둡니다 ... 캡슐화는 이러한 동작을 발생시키는 구현에 중점을 둡니다 ... 캡슐화는 대부분 정보 숨김을 통해 달성됩니다. 본질적인 특성에 기여하지 않는 물건의 비밀.


추상화 는 "관련된"데이터 만 표시하고 사용자로부터 개체의 불필요한 세부 정보를 "숨기는"프로세스입니다. 휴대 전화를 고려하면 메시지를 보내거나 전화를 걸기 위해 어떤 버튼을 눌러야하는지 알면됩니다. 버튼을 누르면 어떻게되는지, 메시지가 어떻게 전송되는지, 전화가 연결되는 방식은 모두 사용자.

캡슐화 는 데이터와 함수를 클래스라는 단일 단위로 결합하는 프로세스입니다. 캡슐화에서 데이터는 직접 액세스되지 않습니다. 클래스 내부에있는 함수를 통해 액세스됩니다. 간단히 말해서, 클래스의 속성은 비공개로 유지되며 이러한 속성을 조작하기 위해 공용 getter 및 setter 메서드가 제공됩니다. 따라서 캡슐화는 데이터 숨김 개념을 가능하게합니다.

여기에 이미지 설명 입력


추상화 는 정보를 숨기거나 클라이언트에게 필요한 세부 정보 만 제공하는 것입니다.

예 : 자동차 브레이크-페달을 밟으면 차량이 멈춘다는 것을 알고 있지만 내부적으로 어떻게 작동하는지 알 필요는 없습니다.

Abstraction의 장점 내일 브레이크 구현이 드럼 브레이크에서 디스크 브레이크로 변경되면 클라이언트로서 변경할 필요가 없습니다 (즉 코드가 변경되지 않음).

캡슐화 는 데이터와 동작을 단일 단위로 묶는 것입니다. 또한 일부 구성 요소에 대한 액세스를 제한하는 언어 메커니즘입니다 (이는 private, protected 등과 같은 액세스 수정 자에 의해 달성 될 수 있음).

예를 들어 클래스 에는 속성 (예 : 데이터) 및 동작 (예 : 해당 데이터에서 작동하는 메서드)이 있습니다.


C #을 사용한 예

//abstraction - exposing only the relevant behavior
public interface IMakeFire
{
     void LightFire();
}

//encapsulation - hiding things that the rest of the world doesn't need to see
public class Caveman: IMakeFire
{
     //exposed information  
     public string Name {get;set;}

     // exposed but unchangeable information
     public byte Age {get; private set;}

     //internal i.e hidden object detail. This can be changed freely, the outside world
     // doesn't know about it
     private bool CanMakeFire()
     {  
         return Age >7;
     }

     //implementation of a relevant feature
     public void LightFire()
     {
        if (!CanMakeFire())
        {
           throw new UnableToLightFireException("Too young");
        }
        GatherWood();
        GetFireStone();
        //light the fire

     }

     private GatherWood() {};
     private GetFireStone();
}

public class PersonWithMatch:IMakeFire
{
      //implementation
 }

IMakeFire '기능'을 구현하기 때문에 원시인 이라면 누구나 불을 지를 수 있습니다. 화재 제작자 그룹 (목록)이 있다는 것은 Caveman과 PersonWithMatch가 모두 유효한 선택임을 의미합니다.

이것은

  //this method (and class) isn't coupled to a Caveman or a PersonWithMatch
  // it can work with ANY object implementing IMakeFire
  public void FireStarter(IMakeFire starter)
  {
        starter.LightFire();
    }

따라서 많은 세부 사항 (속성)과 동작 (방법)을 가진 많은 구현자를 가질 수 있지만이 시나리오에서 중요한 것은 발사 능력입니다. 이것은 추상화입니다.

불을 피우려면 몇 가지 단계 (GetWood 등)가 필요하기 때문에 클래스의 내부 문제이므로 뷰에서 숨겨집니다. 원시인은 외부 세계에서 호출 할 수있는 다른 많은 공공 행동을 가지고 있습니다. 그러나 내부 작업과 관련된 일부 세부 사항은 항상 숨겨집니다. 그들은 사적이며 객체를 위해서만 존재하며 결코 노출되지 않습니다. 이것은 캡슐화입니다.


추상화는 일반화 된 용어입니다. 즉 캡슐화는 추상화의 하위 집합입니다.

추상화 는 복잡한 시스템을 관리하는 강력한 방법입니다. 추상화는 잘 정의 된 객체와 계층 적 분류로 관리됩니다.

예를 들어 자동차 자체는 기어링 시스템, 스티어링 메커니즘, 엔진과 같은 다른 여러 개의 작은 개체로 구성된 잘 정의 된 개체이며, 다시 자체 하위 시스템이 있습니다. 그러나 인간의 경우 자동차는 내부 세부 사항을 알 수없는 경우에도 하위 시스템의 도움으로 관리 할 수있는 단일 개체입니다. 예의


캡슐화 : 데이터 멤버와 메서드를 하나의 단위 (즉, 클래스)로 묶는 것을 캡슐화라고합니다.

캡슐화는 캡슐에 넣는 것과 같습니다. 즉, 개체와 관련된 작업 및 데이터를 해당 개체에 포함합니다.

Encapsulation은 펜, 책 등을 보관할 수있는 가방과 같습니다. 이는 구성원과 기능을 캡슐화하는 속성임을 의미합니다.

class Bag{
    book;
    pen;
    ReadBook();
}

캡슐화는 개체의 내부 세부 정보, 즉 개체가 어떤 작업을 수행하는지 숨기는 것을 의미합니다.

캡슐화는 클라이언트가 추상화 동작이 구현 된 내부보기를 보지 못하도록합니다.

캡슐화는 다른 개체로부터 개체의 정보를 보호하는 데 사용되는 기술입니다.

변수를 비공개로 설정하는 등 보안을 위해 데이터를 숨기고 속성을 노출하여 공개되는 비공개 데이터에 액세스합니다.

따라서 속성에 액세스 할 때 데이터의 유효성을 검사하고 설정할 수 있습니다. 예의


추상화는 디자인에서 캡처 / 표현하려는 엔터티에서 불필요한 세부 정보를 "삭제"하고 도메인과 관련된 엔터티의 속성 만 유지하는 프로세스입니다.
예 : 자동차를 나타내려면 모델 및 가격, 현재 위치 및 현재 속도 등을 유지하고 색상 및 좌석 수 등을 무시합니다.

캡슐화는 단일 추상화 단위 (즉, 클래스)에서 속성과 속성을 조작하는 작업의 "바인딩"입니다.
따라서 자동차는 accelarate stop위치와 현재 속도 등을 조작 할 수 있습니다.


실세계의 예를 들어 추상화를 설명하겠습니다. 집에 전기 플러그가 있고 많은 장치가 동일한 플러그에 연결할 수 있지만 플러그는 어떤 장치에 연결되어 있는지 전혀 알지 못합니다. 즉, 장치의 세부 사항이 플러그에 추상화 (숨겨 짐)됩니다.

플러그없이 장치를 전선에 직접 연결하면 어떨까요? 전구를 와이어에 직접 연결하면 와이어가 연결된 장치를 알고 있으며 전구를 교체해야 할 때마다 전구에서 와이어 연결을 제거해야합니다. 즉, 전구가 와이어와 단단히 연결되어 있음을 의미합니다. 즉, 전구와 와이어는 연결되는 세부 사항을 알고 있으며 추상화되지 않음을 의미합니다.

객체 지향 세계에서 추상화는 정확히 동일하게 작동합니다. 다른 클래스 function / property를 소비하는 클래스는 어떤 클래스가 function / property를 소비하는지 알 필요가 없으며 모든 것이 인터페이스 / 추상 클래스로 추상화되어야합니다.

동일한 예제를 코딩하겠습니다. 여기에 장치를 실행하는 "ElectricPlug"클래스가 있습니다. 그러나 "ElectricPlug"클래스는 어떤 장치가 실행되고 있는지 전혀 모릅니다. "IDevice"인터페이스를 구현하는 모든 클래스가 될 수 있습니다. 이는 "RunDevice"구현이 "ElectricPlug"에서 추상화됨을 의미합니다. 다음은 전체 샘플 코드입니다.

class Program
{
    static void Main(string[] args)
    {
        ElectricPlug electricPlug = new ElectricPlug(new Bulb());
    }
}

public class ElectricPlug
{
    private readonly IDevice _device;
    public ElectricPlug(IDevice device)
    {
        _device = device;
    }

    public void Run()
    {
        _device.Rundevice();
    }
}


public interface IDevice
{
    void Rundevice();
}


public class Bulb : IDevice
{
    public void Rundevice()
    {
       Console.WriteLine("Switched on bulb");
    }
}

Encapsulation is what it sounds like, a way of putting a box around something to protect its contents. Abstraction is extracting the functional properties of something such that you can perform operations using only what you've extracted without knowledge of the inner workings.

When we say that two substances are liquids we are using "liquid" as an abstraction over the properties of those substances we're choosing to discuss. That abstraction tells us the things we can do with the substances given our previous experience with liquids.

Abstraction also doesn't really have anything to do with heirarchies. You can have another abstraction like "metals" that extracts properties of substances in a different way.

Abstractions forget details, so if you're using a particular abstraction you shouldn't ask about properties of the underlying substance that aren't granted by the abstraction. Like if you take milk and water and mix them together, you have a hard time then asking how much milk you have.

A Functor is an abstraction over something that has some notion of map, that is, you can run a function on its inner contents that transforms the inner bit into anything else. The outer something stays the same kind of thing.

Where this gets useful is that if you have a function that works on Lists and you realise you're only depending on the map interface, you can instead depend on Functor and then your function can work with streams, promises, maybes, tuples, and anything else that shares that abstraction.

Functional languages like Haskell have some really great powers of abstraction that make extreme code reuse practical.


Abstraction is like using a computer.

You have absolutely no idea what's going on with it beyond what you see with the GUI (graphical user interface) and external hardware (e.g. screen). All those pretty colors and such. You're only presented the details relevant to you as a generic consumer.

Encapsulation is the actual act of hiding the irrelevant details.

You use your computer, but you don't see what its CPU (central processing unit) looks like (unless you try to break into it). It's hidden (or encapsulated) behind all that chrome and plastic.

In the context of OOP (object-oriented programming) languages, you usually have this kind of setup:

CLASS {
  METHOD { 
    *the actual code*
  }
}

An example of "encapsulation" would be having a METHOD that the regular user can't see (private). "Abstraction" is the regular user using the METHOD that they can (public) in order to use the private one.


Abstraction is a means of hiding details in order to simplify an interface.

So, using a car as an example, all of the controls in a car are abstractions. This allows you to operate a vehicle without understanding the underlying details of the steering, acceleration, or deceleration systems.

A good abstraction is one that standardizes an interface broadly, across multiple instances of a similar problem. A great abstraction can change an industry.

The modern steering wheel, brake pedal, and gas pedal are all examples of great abstractions. Car steering initially looked more like bicycle steering. And both brakes and throttles were operated by hand. But the abstractions we use today were so powerful, they swept the industry.

--

Encapsulation is a means of hiding details in order to protect them from outside manipulation.

Encapsulation is what prevents the driver from manipulating the way the car drives — from the stiffness of the steering, suspension, and braking, to the characteristics of the throttle, and transmission. Most cars do not provide interfaces for changing any of these things. This encapsulation ensures that the vehicle will operate as the manufacturer intended.

Some cars offer a small number of driving modes — like luxury, sport, and economy — which allow the driver to change several of these attributes together at once. By providing driving modes, the manufacturer is allowing the driver some control over the experience while preventing them from selecting a combination of attributes that would render the vehicle less enjoyable or unsafe. In this way, the manufacturer is hiding the details to prevent unsafe manipulations. This is encapsulation.


data abstraction: accessing data members and member functions of any class is simply called data abstraction.....

encapsulation: binding variables and functions or 1 can say data members or member functions all together in a single unit is called as data encapsulation....


Encapsulation can be thought of as wrapping paper used to bind data and function together as a single unit which protects it from all kinds of external dirt (I mean external functions).

Abstraction involves absence of details and the use of a simple interface to control a complex system.

For example we can light a bulb by the pressing of a button without worrying about the underlying electrical engineering (Abstraction) .

However u cannot light the bulb in any other way. (Encapsulation)


public abstract class Draw {
    public abstract void drawShape(); // this is abstraction.  Implementation detail need not to be known.
    // so we are providing only necessary detail by giving drawShape(); No implementation. Subclass will give detail.


    private int type;    // this variable cannot be set outside of the class. Because it is private.
    // Binding private instance variable with public setter/getter method is encapsulation 

    public int getType() { 
        return type;
    }

    public void setType(int type) {  // this is encapsulation. Protecting any value to be set.
        if (type >= 0 && type <= 3) {
            this.type = type;
        } else {
            System.out.println("We have four types only. Enter value between 0 to 4");
            try {
                throw new MyInvalidValueSetException();
            } catch (MyInvalidValueSetException e) {
                e.printStackTrace();
            }

        }
    }
}

Abstraction is related with methods where implementation detail is not known which is a kind of implementation hiding.
Encapsulation is related with instance variable binding with method, a kind of data hiding.


Data Abstraction: DA is simply filtering the concrete item. By the class we can achieve the pure abstraction, because before creating the class we can think only about concerned information about the class.

Encapsulation: It is a mechanism, by which we protect our data from outside.


Abstraction is Showing necessary info to the user where as Encapsulation hide the unwanted data from the user(Product from the user).

Encapsulation Implements the Abstraction.

Abstraction is the process where as Encapsulation actually implements it. For Eg. Adding user logic -> we need to validate the user , creating DB connection and insert the User. So user do not know fist need to call validate function , creating DB connection and then insert the Value in DB. He only call the AddUser function which call the internally all logic with in , this is only Encapsulation (Grouping the feature and hiding the methods).


Encapsulation: I think this is much to do with how you can bind things into one entity rather than hiding. If you choose to hide something you can.

추상화 : 추상화는 숨어있는 것들과 많은 관련이 있으며 다양한 수준의 추상화가있을 수 있습니다. 예를 들어, 기능적 추상화에서 우리는 목록에 항목을 추가 할 수있는 것이 중요하다고 말할 수 있지만 그 방법에 대한 세부 사항은 관심이 없으며 숨겨야합니다. 데이터 추상화를 사용하면 목록이 정보를 저장할 수있는 장소라고 말할 수 있지만 목록이 실제로 구현되는 방법 (예 : 배열 또는 일련의 연결된 위치)은 중요하지 않으며 숨겨야합니다.

참고

참고 URL : https://stackoverflow.com/questions/16014290/simple-way-to-understand-encapsulation-and-abstraction

반응형