1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_BASE_SINGLE_CHILD_H
17 #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_BASE_SINGLE_CHILD_H
18 
19 #include "base/memory/ace_type.h"
20 #include "core/pipeline/base/component.h"
21 
22 namespace OHOS::Ace {
23 
24 class SingleChild : public virtual AceType {
25     DECLARE_ACE_TYPE(SingleChild, AceType);
26 
27 public:
28     SingleChild() = default;
SingleChild(const RefPtr<Component> & child)29     explicit SingleChild(const RefPtr<Component>& child) : child_(child) {}
30     ~SingleChild() override = default;
31 
GetChild()32     const RefPtr<Component>& GetChild() const
33     {
34         return child_;
35     }
36 
SetChild(const RefPtr<Component> & child)37     void SetChild(const RefPtr<Component>& child)
38     {
39         SetChildDirectly(child);
40         if (child) {
41             OnChildAdded(child);
42         }
43     }
44 
SetChildDirectly(const RefPtr<Component> & child)45     void SetChildDirectly(const RefPtr<Component>& child)
46     {
47         // Clear preview child's parent.
48         if (child_) {
49             child_->SetParent(nullptr);
50         }
51 
52         child_ = child;
53 
54         // Set current child's parent.
55         if (child) {
56             auto parent = AceType::DynamicCast<Component>(this);
57             child->SetParent(WeakClaim(parent));
58         }
59     }
60 
OnChildAdded(const RefPtr<Component> & child)61     virtual void OnChildAdded(const RefPtr<Component>& child) {}
62 
63 private:
64     RefPtr<Component> child_;
65 };
66 
67 } // namespace OHOS::Ace
68 
69 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_BASE_SINGLE_CHILD_H
70